babylon.no-module.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * 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".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. 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);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides the current Vector3 coordinates by the given ones.
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * 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"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. 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);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * 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)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * 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
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. 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]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. 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]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. 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);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. 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);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. 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);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. 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);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. 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);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. 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);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * 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"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * 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".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. 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);
  6093. };
  6094. /**
  6095. * 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"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * 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".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. 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);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. 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);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. 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);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. 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);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. 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);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. 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);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. 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);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. 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);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * 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.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. 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)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. 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;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. 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)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * 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.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * 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).
  8129. * 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.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @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.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._observers.splice(index, 1);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._observers.splice(index, 1);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this.remove(observer);
  8218. });
  8219. };
  8220. /**
  8221. * Notify all Observers by calling their respective callback with the given data
  8222. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8223. * @param eventData defines the data to send to all observers
  8224. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8225. * @param target defines the original target of the state
  8226. * @param currentTarget defines the current target of the state
  8227. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8228. */
  8229. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8230. if (mask === void 0) { mask = -1; }
  8231. if (!this._observers.length) {
  8232. return true;
  8233. }
  8234. var state = this._eventState;
  8235. state.mask = mask;
  8236. state.target = target;
  8237. state.currentTarget = currentTarget;
  8238. state.skipNextObservers = false;
  8239. state.lastReturnValue = eventData;
  8240. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8241. var obs = _a[_i];
  8242. if (obs._willBeUnregistered) {
  8243. continue;
  8244. }
  8245. if (obs.mask & mask) {
  8246. if (obs.scope) {
  8247. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8248. }
  8249. else {
  8250. state.lastReturnValue = obs.callback(eventData, state);
  8251. }
  8252. if (obs.unregisterOnNextCall) {
  8253. this._deferUnregister(obs);
  8254. }
  8255. }
  8256. if (state.skipNextObservers) {
  8257. return false;
  8258. }
  8259. }
  8260. return true;
  8261. };
  8262. /**
  8263. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8264. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8265. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8266. * and it is crucial that all callbacks will be executed.
  8267. * The order of the callbacks is kept, callbacks are not executed parallel.
  8268. *
  8269. * @param eventData The data to be sent to each callback
  8270. * @param mask is used to filter observers defaults to -1
  8271. * @param target defines the callback target (see EventState)
  8272. * @param currentTarget defines he current object in the bubbling phase
  8273. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8274. */
  8275. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8276. var _this = this;
  8277. if (mask === void 0) { mask = -1; }
  8278. // create an empty promise
  8279. var p = Promise.resolve(eventData);
  8280. // no observers? return this promise.
  8281. if (!this._observers.length) {
  8282. return p;
  8283. }
  8284. var state = this._eventState;
  8285. state.mask = mask;
  8286. state.target = target;
  8287. state.currentTarget = currentTarget;
  8288. state.skipNextObservers = false;
  8289. // execute one callback after another (not using Promise.all, the order is important)
  8290. this._observers.forEach(function (obs) {
  8291. if (state.skipNextObservers) {
  8292. return;
  8293. }
  8294. if (obs._willBeUnregistered) {
  8295. return;
  8296. }
  8297. if (obs.mask & mask) {
  8298. if (obs.scope) {
  8299. p = p.then(function (lastReturnedValue) {
  8300. state.lastReturnValue = lastReturnedValue;
  8301. return obs.callback.apply(obs.scope, [eventData, state]);
  8302. });
  8303. }
  8304. else {
  8305. p = p.then(function (lastReturnedValue) {
  8306. state.lastReturnValue = lastReturnedValue;
  8307. return obs.callback(eventData, state);
  8308. });
  8309. }
  8310. if (obs.unregisterOnNextCall) {
  8311. _this._deferUnregister(obs);
  8312. }
  8313. }
  8314. });
  8315. // return the eventData
  8316. return p.then(function () { return eventData; });
  8317. };
  8318. /**
  8319. * Notify a specific observer
  8320. * @param observer defines the observer to notify
  8321. * @param eventData defines the data to be sent to each callback
  8322. * @param mask is used to filter observers defaults to -1
  8323. */
  8324. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8325. if (mask === void 0) { mask = -1; }
  8326. var state = this._eventState;
  8327. state.mask = mask;
  8328. state.skipNextObservers = false;
  8329. observer.callback(eventData, state);
  8330. };
  8331. /**
  8332. * Gets a boolean indicating if the observable has at least one observer
  8333. * @returns true is the Observable has at least one Observer registered
  8334. */
  8335. Observable.prototype.hasObservers = function () {
  8336. return this._observers.length > 0;
  8337. };
  8338. /**
  8339. * Clear the list of observers
  8340. */
  8341. Observable.prototype.clear = function () {
  8342. this._observers = new Array();
  8343. this._onObserverAdded = null;
  8344. };
  8345. /**
  8346. * Clone the current observable
  8347. * @returns a new observable
  8348. */
  8349. Observable.prototype.clone = function () {
  8350. var result = new Observable();
  8351. result._observers = this._observers.slice(0);
  8352. return result;
  8353. };
  8354. /**
  8355. * Does this observable handles observer registered with a given mask
  8356. * @param mask defines the mask to be tested
  8357. * @return whether or not one observer registered with the given mask is handeled
  8358. **/
  8359. Observable.prototype.hasSpecificMask = function (mask) {
  8360. if (mask === void 0) { mask = -1; }
  8361. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8362. var obs = _a[_i];
  8363. if (obs.mask & mask || obs.mask === mask) {
  8364. return true;
  8365. }
  8366. }
  8367. return false;
  8368. };
  8369. return Observable;
  8370. }());
  8371. BABYLON.Observable = Observable;
  8372. })(BABYLON || (BABYLON = {}));
  8373. //# sourceMappingURL=babylon.observable.js.map
  8374. var BABYLON;
  8375. (function (BABYLON) {
  8376. var SmartArray = /** @class */ (function () {
  8377. function SmartArray(capacity) {
  8378. this.length = 0;
  8379. this.data = new Array(capacity);
  8380. this._id = SmartArray._GlobalId++;
  8381. }
  8382. SmartArray.prototype.push = function (value) {
  8383. this.data[this.length++] = value;
  8384. if (this.length > this.data.length) {
  8385. this.data.length *= 2;
  8386. }
  8387. };
  8388. SmartArray.prototype.forEach = function (func) {
  8389. for (var index = 0; index < this.length; index++) {
  8390. func(this.data[index]);
  8391. }
  8392. };
  8393. SmartArray.prototype.sort = function (compareFn) {
  8394. this.data.sort(compareFn);
  8395. };
  8396. SmartArray.prototype.reset = function () {
  8397. this.length = 0;
  8398. };
  8399. SmartArray.prototype.dispose = function () {
  8400. this.reset();
  8401. if (this.data) {
  8402. this.data.length = 0;
  8403. this.data = [];
  8404. }
  8405. };
  8406. SmartArray.prototype.concat = function (array) {
  8407. if (array.length === 0) {
  8408. return;
  8409. }
  8410. if (this.length + array.length > this.data.length) {
  8411. this.data.length = (this.length + array.length) * 2;
  8412. }
  8413. for (var index = 0; index < array.length; index++) {
  8414. this.data[this.length++] = (array.data || array)[index];
  8415. }
  8416. };
  8417. SmartArray.prototype.indexOf = function (value) {
  8418. var position = this.data.indexOf(value);
  8419. if (position >= this.length) {
  8420. return -1;
  8421. }
  8422. return position;
  8423. };
  8424. SmartArray.prototype.contains = function (value) {
  8425. return this.data.indexOf(value) !== -1;
  8426. };
  8427. // Statics
  8428. SmartArray._GlobalId = 0;
  8429. return SmartArray;
  8430. }());
  8431. BABYLON.SmartArray = SmartArray;
  8432. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8433. __extends(SmartArrayNoDuplicate, _super);
  8434. function SmartArrayNoDuplicate() {
  8435. var _this = _super !== null && _super.apply(this, arguments) || this;
  8436. _this._duplicateId = 0;
  8437. return _this;
  8438. }
  8439. SmartArrayNoDuplicate.prototype.push = function (value) {
  8440. _super.prototype.push.call(this, value);
  8441. if (!value.__smartArrayFlags) {
  8442. value.__smartArrayFlags = {};
  8443. }
  8444. value.__smartArrayFlags[this._id] = this._duplicateId;
  8445. };
  8446. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8447. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8448. return false;
  8449. }
  8450. this.push(value);
  8451. return true;
  8452. };
  8453. SmartArrayNoDuplicate.prototype.reset = function () {
  8454. _super.prototype.reset.call(this);
  8455. this._duplicateId++;
  8456. };
  8457. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8458. if (array.length === 0) {
  8459. return;
  8460. }
  8461. if (this.length + array.length > this.data.length) {
  8462. this.data.length = (this.length + array.length) * 2;
  8463. }
  8464. for (var index = 0; index < array.length; index++) {
  8465. var item = (array.data || array)[index];
  8466. this.pushNoDuplicate(item);
  8467. }
  8468. };
  8469. return SmartArrayNoDuplicate;
  8470. }(SmartArray));
  8471. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8472. })(BABYLON || (BABYLON = {}));
  8473. //# sourceMappingURL=babylon.smartArray.js.map
  8474. var BABYLON;
  8475. (function (BABYLON) {
  8476. /** Class used to store color gradient */
  8477. var ColorGradient = /** @class */ (function () {
  8478. function ColorGradient() {
  8479. }
  8480. /**
  8481. * Will get a color picked randomly between color1 and color2.
  8482. * If color2 is undefined then color1 will be used
  8483. * @param result defines the target Color4 to store the result in
  8484. */
  8485. ColorGradient.prototype.getColorToRef = function (result) {
  8486. if (!this.color2) {
  8487. result.copyFrom(this.color1);
  8488. return;
  8489. }
  8490. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8491. };
  8492. return ColorGradient;
  8493. }());
  8494. BABYLON.ColorGradient = ColorGradient;
  8495. /** Class used to store factor gradient */
  8496. var FactorGradient = /** @class */ (function () {
  8497. function FactorGradient() {
  8498. }
  8499. return FactorGradient;
  8500. }());
  8501. BABYLON.FactorGradient = FactorGradient;
  8502. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8503. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8504. var LoadFileError = /** @class */ (function (_super) {
  8505. __extends(LoadFileError, _super);
  8506. function LoadFileError(message, request) {
  8507. var _this = _super.call(this, message) || this;
  8508. _this.request = request;
  8509. _this.name = "LoadFileError";
  8510. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8511. return _this;
  8512. }
  8513. // Polyfill for Object.setPrototypeOf if necessary.
  8514. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8515. return LoadFileError;
  8516. }(Error));
  8517. BABYLON.LoadFileError = LoadFileError;
  8518. var RetryStrategy = /** @class */ (function () {
  8519. function RetryStrategy() {
  8520. }
  8521. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8522. if (maxRetries === void 0) { maxRetries = 3; }
  8523. if (baseInterval === void 0) { baseInterval = 500; }
  8524. return function (url, request, retryIndex) {
  8525. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8526. return -1;
  8527. }
  8528. return Math.pow(2, retryIndex) * baseInterval;
  8529. };
  8530. };
  8531. return RetryStrategy;
  8532. }());
  8533. BABYLON.RetryStrategy = RetryStrategy;
  8534. // Screenshots
  8535. var screenshotCanvas;
  8536. var cloneValue = function (source, destinationObject) {
  8537. if (!source)
  8538. return null;
  8539. if (source instanceof BABYLON.Mesh) {
  8540. return null;
  8541. }
  8542. if (source instanceof BABYLON.SubMesh) {
  8543. return source.clone(destinationObject);
  8544. }
  8545. else if (source.clone) {
  8546. return source.clone();
  8547. }
  8548. return null;
  8549. };
  8550. var Tools = /** @class */ (function () {
  8551. function Tools() {
  8552. }
  8553. /**
  8554. * Interpolates between a and b via alpha
  8555. * @param a The lower value (returned when alpha = 0)
  8556. * @param b The upper value (returned when alpha = 1)
  8557. * @param alpha The interpolation-factor
  8558. * @return The mixed value
  8559. */
  8560. Tools.Mix = function (a, b, alpha) {
  8561. return a * (1 - alpha) + b * alpha;
  8562. };
  8563. Tools.Instantiate = function (className) {
  8564. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8565. return Tools.RegisteredExternalClasses[className];
  8566. }
  8567. var arr = className.split(".");
  8568. var fn = (window || this);
  8569. for (var i = 0, len = arr.length; i < len; i++) {
  8570. fn = fn[arr[i]];
  8571. }
  8572. if (typeof fn !== "function") {
  8573. return null;
  8574. }
  8575. return fn;
  8576. };
  8577. /**
  8578. * Provides a slice function that will work even on IE
  8579. * @param data defines the array to slice
  8580. * @param start defines the start of the data (optional)
  8581. * @param end defines the end of the data (optional)
  8582. * @returns the new sliced array
  8583. */
  8584. Tools.Slice = function (data, start, end) {
  8585. if (data.slice) {
  8586. return data.slice(start, end);
  8587. }
  8588. return Array.prototype.slice.call(data, start, end);
  8589. };
  8590. Tools.SetImmediate = function (action) {
  8591. if (window.setImmediate) {
  8592. window.setImmediate(action);
  8593. }
  8594. else {
  8595. setTimeout(action, 1);
  8596. }
  8597. };
  8598. Tools.IsExponentOfTwo = function (value) {
  8599. var count = 1;
  8600. do {
  8601. count *= 2;
  8602. } while (count < value);
  8603. return count === value;
  8604. };
  8605. /**
  8606. * Returns the nearest 32-bit single precision float representation of a Number
  8607. * @param value A Number. If the parameter is of a different type, it will get converted
  8608. * to a number or to NaN if it cannot be converted
  8609. * @returns number
  8610. */
  8611. Tools.FloatRound = function (value) {
  8612. if (Math.fround) {
  8613. return Math.fround(value);
  8614. }
  8615. return (Tools._tmpFloatArray[0] = value);
  8616. };
  8617. /**
  8618. * Find the next highest power of two.
  8619. * @param x Number to start search from.
  8620. * @return Next highest power of two.
  8621. */
  8622. Tools.CeilingPOT = function (x) {
  8623. x--;
  8624. x |= x >> 1;
  8625. x |= x >> 2;
  8626. x |= x >> 4;
  8627. x |= x >> 8;
  8628. x |= x >> 16;
  8629. x++;
  8630. return x;
  8631. };
  8632. /**
  8633. * Find the next lowest power of two.
  8634. * @param x Number to start search from.
  8635. * @return Next lowest power of two.
  8636. */
  8637. Tools.FloorPOT = function (x) {
  8638. x = x | (x >> 1);
  8639. x = x | (x >> 2);
  8640. x = x | (x >> 4);
  8641. x = x | (x >> 8);
  8642. x = x | (x >> 16);
  8643. return x - (x >> 1);
  8644. };
  8645. /**
  8646. * Find the nearest power of two.
  8647. * @param x Number to start search from.
  8648. * @return Next nearest power of two.
  8649. */
  8650. Tools.NearestPOT = function (x) {
  8651. var c = Tools.CeilingPOT(x);
  8652. var f = Tools.FloorPOT(x);
  8653. return (c - x) > (x - f) ? f : c;
  8654. };
  8655. Tools.GetExponentOfTwo = function (value, max, mode) {
  8656. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8657. var pot;
  8658. switch (mode) {
  8659. case BABYLON.Engine.SCALEMODE_FLOOR:
  8660. pot = Tools.FloorPOT(value);
  8661. break;
  8662. case BABYLON.Engine.SCALEMODE_NEAREST:
  8663. pot = Tools.NearestPOT(value);
  8664. break;
  8665. case BABYLON.Engine.SCALEMODE_CEILING:
  8666. default:
  8667. pot = Tools.CeilingPOT(value);
  8668. break;
  8669. }
  8670. return Math.min(pot, max);
  8671. };
  8672. Tools.GetFilename = function (path) {
  8673. var index = path.lastIndexOf("/");
  8674. if (index < 0)
  8675. return path;
  8676. return path.substring(index + 1);
  8677. };
  8678. /**
  8679. * Extracts the "folder" part of a path (everything before the filename).
  8680. * @param uri The URI to extract the info from
  8681. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8682. * @returns The "folder" part of the path
  8683. */
  8684. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8685. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8686. var index = uri.lastIndexOf("/");
  8687. if (index < 0) {
  8688. if (returnUnchangedIfNoSlash) {
  8689. return uri;
  8690. }
  8691. return "";
  8692. }
  8693. return uri.substring(0, index + 1);
  8694. };
  8695. Tools.GetDOMTextContent = function (element) {
  8696. var result = "";
  8697. var child = element.firstChild;
  8698. while (child) {
  8699. if (child.nodeType === 3) {
  8700. result += child.textContent;
  8701. }
  8702. child = child.nextSibling;
  8703. }
  8704. return result;
  8705. };
  8706. Tools.ToDegrees = function (angle) {
  8707. return angle * 180 / Math.PI;
  8708. };
  8709. Tools.ToRadians = function (angle) {
  8710. return angle * Math.PI / 180;
  8711. };
  8712. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8713. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8714. var output = "";
  8715. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8716. var i = 0;
  8717. var bytes = new Uint8Array(buffer);
  8718. while (i < bytes.length) {
  8719. chr1 = bytes[i++];
  8720. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8721. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8722. enc1 = chr1 >> 2;
  8723. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8724. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8725. enc4 = chr3 & 63;
  8726. if (isNaN(chr2)) {
  8727. enc3 = enc4 = 64;
  8728. }
  8729. else if (isNaN(chr3)) {
  8730. enc4 = 64;
  8731. }
  8732. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8733. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8734. }
  8735. return "data:image/png;base64," + output;
  8736. };
  8737. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8738. if (bias === void 0) { bias = null; }
  8739. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8740. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8741. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8742. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8743. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8744. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8745. }
  8746. if (bias) {
  8747. minimum.x -= minimum.x * bias.x + bias.y;
  8748. minimum.y -= minimum.y * bias.x + bias.y;
  8749. minimum.z -= minimum.z * bias.x + bias.y;
  8750. maximum.x += maximum.x * bias.x + bias.y;
  8751. maximum.y += maximum.y * bias.x + bias.y;
  8752. maximum.z += maximum.z * bias.x + bias.y;
  8753. }
  8754. return {
  8755. minimum: minimum,
  8756. maximum: maximum
  8757. };
  8758. };
  8759. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8760. if (bias === void 0) { bias = null; }
  8761. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8762. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8763. if (!stride) {
  8764. stride = 3;
  8765. }
  8766. for (var index = start; index < start + count; index++) {
  8767. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8768. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8769. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8770. }
  8771. if (bias) {
  8772. minimum.x -= minimum.x * bias.x + bias.y;
  8773. minimum.y -= minimum.y * bias.x + bias.y;
  8774. minimum.z -= minimum.z * bias.x + bias.y;
  8775. maximum.x += maximum.x * bias.x + bias.y;
  8776. maximum.y += maximum.y * bias.x + bias.y;
  8777. maximum.z += maximum.z * bias.x + bias.y;
  8778. }
  8779. return {
  8780. minimum: minimum,
  8781. maximum: maximum
  8782. };
  8783. };
  8784. Tools.Vector2ArrayFeeder = function (array) {
  8785. return function (index) {
  8786. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8787. var length = isFloatArray ? array.length / 2 : array.length;
  8788. if (index >= length) {
  8789. return null;
  8790. }
  8791. if (isFloatArray) {
  8792. var fa = array;
  8793. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8794. }
  8795. var a = array;
  8796. return a[index];
  8797. };
  8798. };
  8799. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8800. if (bias === void 0) { bias = null; }
  8801. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8802. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8803. var i = 0;
  8804. var cur = feeder(i++);
  8805. while (cur) {
  8806. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8807. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8808. cur = feeder(i++);
  8809. }
  8810. if (bias) {
  8811. minimum.x -= minimum.x * bias.x + bias.y;
  8812. minimum.y -= minimum.y * bias.x + bias.y;
  8813. maximum.x += maximum.x * bias.x + bias.y;
  8814. maximum.y += maximum.y * bias.x + bias.y;
  8815. }
  8816. return {
  8817. minimum: minimum,
  8818. maximum: maximum
  8819. };
  8820. };
  8821. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8822. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8823. return null;
  8824. return Array.isArray(obj) ? obj : [obj];
  8825. };
  8826. // Misc.
  8827. Tools.GetPointerPrefix = function () {
  8828. var eventPrefix = "pointer";
  8829. // Check if pointer events are supported
  8830. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8831. eventPrefix = "mouse";
  8832. }
  8833. return eventPrefix;
  8834. };
  8835. /**
  8836. * @param func - the function to be called
  8837. * @param requester - the object that will request the next frame. Falls back to window.
  8838. */
  8839. Tools.QueueNewFrame = function (func, requester) {
  8840. if (!Tools.IsWindowObjectExist()) {
  8841. return setTimeout(func, 16);
  8842. }
  8843. if (!requester) {
  8844. requester = window;
  8845. }
  8846. if (requester.requestAnimationFrame) {
  8847. return requester.requestAnimationFrame(func);
  8848. }
  8849. else if (requester.msRequestAnimationFrame) {
  8850. return requester.msRequestAnimationFrame(func);
  8851. }
  8852. else if (requester.webkitRequestAnimationFrame) {
  8853. return requester.webkitRequestAnimationFrame(func);
  8854. }
  8855. else if (requester.mozRequestAnimationFrame) {
  8856. return requester.mozRequestAnimationFrame(func);
  8857. }
  8858. else if (requester.oRequestAnimationFrame) {
  8859. return requester.oRequestAnimationFrame(func);
  8860. }
  8861. else {
  8862. return window.setTimeout(func, 16);
  8863. }
  8864. };
  8865. Tools.RequestFullscreen = function (element) {
  8866. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8867. if (!requestFunction)
  8868. return;
  8869. requestFunction.call(element);
  8870. };
  8871. Tools.ExitFullscreen = function () {
  8872. if (document.exitFullscreen) {
  8873. document.exitFullscreen();
  8874. }
  8875. else if (document.mozCancelFullScreen) {
  8876. document.mozCancelFullScreen();
  8877. }
  8878. else if (document.webkitCancelFullScreen) {
  8879. document.webkitCancelFullScreen();
  8880. }
  8881. else if (document.msCancelFullScreen) {
  8882. document.msCancelFullScreen();
  8883. }
  8884. };
  8885. Tools.SetCorsBehavior = function (url, element) {
  8886. if (url && url.indexOf("data:") === 0) {
  8887. return;
  8888. }
  8889. if (Tools.CorsBehavior) {
  8890. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8891. element.crossOrigin = Tools.CorsBehavior;
  8892. }
  8893. else {
  8894. var result = Tools.CorsBehavior(url);
  8895. if (result) {
  8896. element.crossOrigin = result;
  8897. }
  8898. }
  8899. }
  8900. };
  8901. // External files
  8902. Tools.CleanUrl = function (url) {
  8903. url = url.replace(/#/mg, "%23");
  8904. return url;
  8905. };
  8906. /**
  8907. * Loads an image as an HTMLImageElement.
  8908. * @param input url string, ArrayBuffer, or Blob to load
  8909. * @param onLoad callback called when the image successfully loads
  8910. * @param onError callback called when the image fails to load
  8911. * @param database database for caching
  8912. * @returns the HTMLImageElement of the loaded image
  8913. */
  8914. Tools.LoadImage = function (input, onLoad, onError, database) {
  8915. var url;
  8916. var usingObjectURL = false;
  8917. if (input instanceof ArrayBuffer) {
  8918. url = URL.createObjectURL(new Blob([input]));
  8919. usingObjectURL = true;
  8920. }
  8921. else if (input instanceof Blob) {
  8922. url = URL.createObjectURL(input);
  8923. usingObjectURL = true;
  8924. }
  8925. else {
  8926. url = Tools.CleanUrl(input);
  8927. url = Tools.PreprocessUrl(input);
  8928. }
  8929. var img = new Image();
  8930. Tools.SetCorsBehavior(url, img);
  8931. var loadHandler = function () {
  8932. if (usingObjectURL && img.src) {
  8933. URL.revokeObjectURL(img.src);
  8934. }
  8935. img.removeEventListener("load", loadHandler);
  8936. img.removeEventListener("error", errorHandler);
  8937. onLoad(img);
  8938. };
  8939. var errorHandler = function (err) {
  8940. if (usingObjectURL && img.src) {
  8941. URL.revokeObjectURL(img.src);
  8942. }
  8943. img.removeEventListener("load", loadHandler);
  8944. img.removeEventListener("error", errorHandler);
  8945. Tools.Error("Error while trying to load image: " + input);
  8946. if (onError) {
  8947. onError("Error while trying to load image: " + input, err);
  8948. }
  8949. };
  8950. img.addEventListener("load", loadHandler);
  8951. img.addEventListener("error", errorHandler);
  8952. var noIndexedDB = function () {
  8953. img.src = url;
  8954. };
  8955. var loadFromIndexedDB = function () {
  8956. if (database) {
  8957. database.loadImageFromDB(url, img);
  8958. }
  8959. };
  8960. //ANY database to do!
  8961. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8962. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8963. }
  8964. else {
  8965. if (url.indexOf("file:") !== -1) {
  8966. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8967. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8968. try {
  8969. var blobURL;
  8970. try {
  8971. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8972. }
  8973. catch (ex) {
  8974. // Chrome doesn't support oneTimeOnly parameter
  8975. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8976. }
  8977. img.src = blobURL;
  8978. usingObjectURL = true;
  8979. }
  8980. catch (e) {
  8981. img.src = "";
  8982. }
  8983. return img;
  8984. }
  8985. }
  8986. noIndexedDB();
  8987. }
  8988. return img;
  8989. };
  8990. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8991. url = Tools.CleanUrl(url);
  8992. url = Tools.PreprocessUrl(url);
  8993. // If file and file input are set
  8994. if (url.indexOf("file:") !== -1) {
  8995. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8996. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8997. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8998. }
  8999. }
  9000. var loadUrl = Tools.BaseUrl + url;
  9001. var aborted = false;
  9002. var fileRequest = {
  9003. onCompleteObservable: new BABYLON.Observable(),
  9004. abort: function () { return aborted = true; },
  9005. };
  9006. var requestFile = function () {
  9007. var request = new XMLHttpRequest();
  9008. var retryHandle = null;
  9009. fileRequest.abort = function () {
  9010. aborted = true;
  9011. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9012. request.abort();
  9013. }
  9014. if (retryHandle !== null) {
  9015. clearTimeout(retryHandle);
  9016. retryHandle = null;
  9017. }
  9018. };
  9019. var retryLoop = function (retryIndex) {
  9020. request.open('GET', loadUrl, true);
  9021. if (useArrayBuffer) {
  9022. request.responseType = "arraybuffer";
  9023. }
  9024. if (onProgress) {
  9025. request.addEventListener("progress", onProgress);
  9026. }
  9027. var onLoadEnd = function () {
  9028. request.removeEventListener("loadend", onLoadEnd);
  9029. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9030. fileRequest.onCompleteObservable.clear();
  9031. };
  9032. request.addEventListener("loadend", onLoadEnd);
  9033. var onReadyStateChange = function () {
  9034. if (aborted) {
  9035. return;
  9036. }
  9037. // In case of undefined state in some browsers.
  9038. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9039. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9040. request.removeEventListener("readystatechange", onReadyStateChange);
  9041. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9042. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9043. return;
  9044. }
  9045. var retryStrategy = Tools.DefaultRetryStrategy;
  9046. if (retryStrategy) {
  9047. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9048. if (waitTime !== -1) {
  9049. // Prevent the request from completing for retry.
  9050. request.removeEventListener("loadend", onLoadEnd);
  9051. request = new XMLHttpRequest();
  9052. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9053. return;
  9054. }
  9055. }
  9056. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9057. if (onError) {
  9058. onError(request, e);
  9059. }
  9060. else {
  9061. throw e;
  9062. }
  9063. }
  9064. };
  9065. request.addEventListener("readystatechange", onReadyStateChange);
  9066. request.send();
  9067. };
  9068. retryLoop(0);
  9069. };
  9070. // Caching all files
  9071. if (database && database.enableSceneOffline) {
  9072. var noIndexedDB_1 = function () {
  9073. if (!aborted) {
  9074. requestFile();
  9075. }
  9076. };
  9077. var loadFromIndexedDB = function () {
  9078. // TODO: database needs to support aborting and should return a IFileRequest
  9079. if (aborted) {
  9080. return;
  9081. }
  9082. if (database) {
  9083. database.loadFileFromDB(url, function (data) {
  9084. if (!aborted) {
  9085. onSuccess(data);
  9086. }
  9087. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9088. }, onProgress ? function (event) {
  9089. if (!aborted) {
  9090. onProgress(event);
  9091. }
  9092. } : undefined, noIndexedDB_1, useArrayBuffer);
  9093. }
  9094. };
  9095. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9096. }
  9097. else {
  9098. requestFile();
  9099. }
  9100. return fileRequest;
  9101. };
  9102. /**
  9103. * Load a script (identified by an url). When the url returns, the
  9104. * content of this file is added into a new script element, attached to the DOM (body element)
  9105. */
  9106. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9107. var head = document.getElementsByTagName('head')[0];
  9108. var script = document.createElement('script');
  9109. script.type = 'text/javascript';
  9110. script.src = scriptUrl;
  9111. script.onload = function () {
  9112. if (onSuccess) {
  9113. onSuccess();
  9114. }
  9115. };
  9116. script.onerror = function (e) {
  9117. if (onError) {
  9118. onError("Unable to load script '" + scriptUrl + "'", e);
  9119. }
  9120. };
  9121. head.appendChild(script);
  9122. };
  9123. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9124. var reader = new FileReader();
  9125. var request = {
  9126. onCompleteObservable: new BABYLON.Observable(),
  9127. abort: function () { return reader.abort(); },
  9128. };
  9129. reader.onloadend = function (e) {
  9130. request.onCompleteObservable.notifyObservers(request);
  9131. };
  9132. reader.onload = function (e) {
  9133. //target doesn't have result from ts 1.3
  9134. callback(e.target['result']);
  9135. };
  9136. reader.onprogress = progressCallback;
  9137. reader.readAsDataURL(fileToLoad);
  9138. return request;
  9139. };
  9140. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9141. var reader = new FileReader();
  9142. var request = {
  9143. onCompleteObservable: new BABYLON.Observable(),
  9144. abort: function () { return reader.abort(); },
  9145. };
  9146. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9147. reader.onerror = function (e) {
  9148. Tools.Log("Error while reading file: " + fileToLoad.name);
  9149. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9150. };
  9151. reader.onload = function (e) {
  9152. //target doesn't have result from ts 1.3
  9153. callback(e.target['result']);
  9154. };
  9155. if (progressCallBack) {
  9156. reader.onprogress = progressCallBack;
  9157. }
  9158. if (!useArrayBuffer) {
  9159. // Asynchronous read
  9160. reader.readAsText(fileToLoad);
  9161. }
  9162. else {
  9163. reader.readAsArrayBuffer(fileToLoad);
  9164. }
  9165. return request;
  9166. };
  9167. //returns a downloadable url to a file content.
  9168. Tools.FileAsURL = function (content) {
  9169. var fileBlob = new Blob([content]);
  9170. var url = window.URL || window.webkitURL;
  9171. var link = url.createObjectURL(fileBlob);
  9172. return link;
  9173. };
  9174. // Misc.
  9175. Tools.Format = function (value, decimals) {
  9176. if (decimals === void 0) { decimals = 2; }
  9177. return value.toFixed(decimals);
  9178. };
  9179. Tools.CheckExtends = function (v, min, max) {
  9180. if (v.x < min.x)
  9181. min.x = v.x;
  9182. if (v.y < min.y)
  9183. min.y = v.y;
  9184. if (v.z < min.z)
  9185. min.z = v.z;
  9186. if (v.x > max.x)
  9187. max.x = v.x;
  9188. if (v.y > max.y)
  9189. max.y = v.y;
  9190. if (v.z > max.z)
  9191. max.z = v.z;
  9192. };
  9193. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9194. for (var prop in source) {
  9195. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9196. continue;
  9197. }
  9198. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9199. continue;
  9200. }
  9201. var sourceValue = source[prop];
  9202. var typeOfSourceValue = typeof sourceValue;
  9203. if (typeOfSourceValue === "function") {
  9204. continue;
  9205. }
  9206. try {
  9207. if (typeOfSourceValue === "object") {
  9208. if (sourceValue instanceof Array) {
  9209. destination[prop] = [];
  9210. if (sourceValue.length > 0) {
  9211. if (typeof sourceValue[0] == "object") {
  9212. for (var index = 0; index < sourceValue.length; index++) {
  9213. var clonedValue = cloneValue(sourceValue[index], destination);
  9214. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9215. destination[prop].push(clonedValue);
  9216. }
  9217. }
  9218. }
  9219. else {
  9220. destination[prop] = sourceValue.slice(0);
  9221. }
  9222. }
  9223. }
  9224. else {
  9225. destination[prop] = cloneValue(sourceValue, destination);
  9226. }
  9227. }
  9228. else {
  9229. destination[prop] = sourceValue;
  9230. }
  9231. }
  9232. catch (e) {
  9233. // Just ignore error (it could be because of a read-only property)
  9234. }
  9235. }
  9236. };
  9237. Tools.IsEmpty = function (obj) {
  9238. for (var i in obj) {
  9239. if (obj.hasOwnProperty(i)) {
  9240. return false;
  9241. }
  9242. }
  9243. return true;
  9244. };
  9245. Tools.RegisterTopRootEvents = function (events) {
  9246. for (var index = 0; index < events.length; index++) {
  9247. var event = events[index];
  9248. window.addEventListener(event.name, event.handler, false);
  9249. try {
  9250. if (window.parent) {
  9251. window.parent.addEventListener(event.name, event.handler, false);
  9252. }
  9253. }
  9254. catch (e) {
  9255. // Silently fails...
  9256. }
  9257. }
  9258. };
  9259. Tools.UnregisterTopRootEvents = function (events) {
  9260. for (var index = 0; index < events.length; index++) {
  9261. var event = events[index];
  9262. window.removeEventListener(event.name, event.handler);
  9263. try {
  9264. if (window.parent) {
  9265. window.parent.removeEventListener(event.name, event.handler);
  9266. }
  9267. }
  9268. catch (e) {
  9269. // Silently fails...
  9270. }
  9271. }
  9272. };
  9273. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9274. if (mimeType === void 0) { mimeType = "image/png"; }
  9275. // Read the contents of the framebuffer
  9276. var numberOfChannelsByLine = width * 4;
  9277. var halfHeight = height / 2;
  9278. //Reading datas from WebGL
  9279. var data = engine.readPixels(0, 0, width, height);
  9280. //To flip image on Y axis.
  9281. for (var i = 0; i < halfHeight; i++) {
  9282. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9283. var currentCell = j + i * numberOfChannelsByLine;
  9284. var targetLine = height - i - 1;
  9285. var targetCell = j + targetLine * numberOfChannelsByLine;
  9286. var temp = data[currentCell];
  9287. data[currentCell] = data[targetCell];
  9288. data[targetCell] = temp;
  9289. }
  9290. }
  9291. // Create a 2D canvas to store the result
  9292. if (!screenshotCanvas) {
  9293. screenshotCanvas = document.createElement('canvas');
  9294. }
  9295. screenshotCanvas.width = width;
  9296. screenshotCanvas.height = height;
  9297. var context = screenshotCanvas.getContext('2d');
  9298. if (context) {
  9299. // Copy the pixels to a 2D canvas
  9300. var imageData = context.createImageData(width, height);
  9301. var castData = (imageData.data);
  9302. castData.set(data);
  9303. context.putImageData(imageData, 0, 0);
  9304. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9305. }
  9306. };
  9307. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9308. if (mimeType === void 0) { mimeType = "image/png"; }
  9309. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9310. if (successCallback) {
  9311. successCallback(base64Image);
  9312. }
  9313. else {
  9314. // We need HTMLCanvasElement.toBlob for HD screenshots
  9315. if (!screenshotCanvas.toBlob) {
  9316. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9317. screenshotCanvas.toBlob = function (callback, type, quality) {
  9318. var _this = this;
  9319. setTimeout(function () {
  9320. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9321. for (var i = 0; i < len; i++) {
  9322. arr[i] = binStr.charCodeAt(i);
  9323. }
  9324. callback(new Blob([arr], { type: type || 'image/png' }));
  9325. });
  9326. };
  9327. }
  9328. screenshotCanvas.toBlob(function (blob) {
  9329. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9330. if (("download" in document.createElement("a"))) {
  9331. if (!fileName) {
  9332. var date = new Date();
  9333. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9334. fileName = "screenshot_" + stringDate + ".png";
  9335. }
  9336. Tools.Download(blob, fileName);
  9337. }
  9338. else {
  9339. var url = URL.createObjectURL(blob);
  9340. var newWindow = window.open("");
  9341. if (!newWindow)
  9342. return;
  9343. var img = newWindow.document.createElement("img");
  9344. img.onload = function () {
  9345. // no longer need to read the blob so it's revoked
  9346. URL.revokeObjectURL(url);
  9347. };
  9348. img.src = url;
  9349. newWindow.document.body.appendChild(img);
  9350. }
  9351. });
  9352. }
  9353. };
  9354. /**
  9355. * Downloads a blob in the browser
  9356. * @param blob defines the blob to download
  9357. * @param fileName defines the name of the downloaded file
  9358. */
  9359. Tools.Download = function (blob, fileName) {
  9360. var url = window.URL.createObjectURL(blob);
  9361. var a = document.createElement("a");
  9362. document.body.appendChild(a);
  9363. a.style.display = "none";
  9364. a.href = url;
  9365. a.download = fileName;
  9366. a.addEventListener("click", function () {
  9367. if (a.parentElement) {
  9368. a.parentElement.removeChild(a);
  9369. }
  9370. });
  9371. a.click();
  9372. window.URL.revokeObjectURL(url);
  9373. };
  9374. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9375. if (mimeType === void 0) { mimeType = "image/png"; }
  9376. var width;
  9377. var height;
  9378. // If a precision value is specified
  9379. if (size.precision) {
  9380. width = Math.round(engine.getRenderWidth() * size.precision);
  9381. height = Math.round(width / engine.getAspectRatio(camera));
  9382. }
  9383. else if (size.width && size.height) {
  9384. width = size.width;
  9385. height = size.height;
  9386. }
  9387. //If passing only width, computing height to keep display canvas ratio.
  9388. else if (size.width && !size.height) {
  9389. width = size.width;
  9390. height = Math.round(width / engine.getAspectRatio(camera));
  9391. }
  9392. //If passing only height, computing width to keep display canvas ratio.
  9393. else if (size.height && !size.width) {
  9394. height = size.height;
  9395. width = Math.round(height * engine.getAspectRatio(camera));
  9396. }
  9397. //Assuming here that "size" parameter is a number
  9398. else if (!isNaN(size)) {
  9399. height = size;
  9400. width = size;
  9401. }
  9402. else {
  9403. Tools.Error("Invalid 'size' parameter !");
  9404. return;
  9405. }
  9406. if (!screenshotCanvas) {
  9407. screenshotCanvas = document.createElement('canvas');
  9408. }
  9409. screenshotCanvas.width = width;
  9410. screenshotCanvas.height = height;
  9411. var renderContext = screenshotCanvas.getContext("2d");
  9412. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9413. var newWidth = width;
  9414. var newHeight = newWidth / ratio;
  9415. if (newHeight > height) {
  9416. newHeight = height;
  9417. newWidth = newHeight * ratio;
  9418. }
  9419. var offsetX = Math.max(0, width - newWidth) / 2;
  9420. var offsetY = Math.max(0, height - newHeight) / 2;
  9421. var renderingCanvas = engine.getRenderingCanvas();
  9422. if (renderContext && renderingCanvas) {
  9423. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9424. }
  9425. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9426. };
  9427. /**
  9428. * Generates an image screenshot from the specified camera.
  9429. *
  9430. * @param engine The engine to use for rendering
  9431. * @param camera The camera to use for rendering
  9432. * @param size This parameter can be set to a single number or to an object with the
  9433. * following (optional) properties: precision, width, height. If a single number is passed,
  9434. * it will be used for both width and height. If an object is passed, the screenshot size
  9435. * will be derived from the parameters. The precision property is a multiplier allowing
  9436. * rendering at a higher or lower resolution.
  9437. * @param successCallback The callback receives a single parameter which contains the
  9438. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9439. * src parameter of an <img> to display it.
  9440. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9441. * Check your browser for supported MIME types.
  9442. * @param samples Texture samples (default: 1)
  9443. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9444. * @param fileName A name for for the downloaded file.
  9445. * @constructor
  9446. */
  9447. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9448. if (mimeType === void 0) { mimeType = "image/png"; }
  9449. if (samples === void 0) { samples = 1; }
  9450. if (antialiasing === void 0) { antialiasing = false; }
  9451. var width;
  9452. var height;
  9453. //If a precision value is specified
  9454. if (size.precision) {
  9455. width = Math.round(engine.getRenderWidth() * size.precision);
  9456. height = Math.round(width / engine.getAspectRatio(camera));
  9457. size = { width: width, height: height };
  9458. }
  9459. else if (size.width && size.height) {
  9460. width = size.width;
  9461. height = size.height;
  9462. }
  9463. //If passing only width, computing height to keep display canvas ratio.
  9464. else if (size.width && !size.height) {
  9465. width = size.width;
  9466. height = Math.round(width / engine.getAspectRatio(camera));
  9467. size = { width: width, height: height };
  9468. }
  9469. //If passing only height, computing width to keep display canvas ratio.
  9470. else if (size.height && !size.width) {
  9471. height = size.height;
  9472. width = Math.round(height * engine.getAspectRatio(camera));
  9473. size = { width: width, height: height };
  9474. }
  9475. //Assuming here that "size" parameter is a number
  9476. else if (!isNaN(size)) {
  9477. height = size;
  9478. width = size;
  9479. }
  9480. else {
  9481. Tools.Error("Invalid 'size' parameter !");
  9482. return;
  9483. }
  9484. var scene = camera.getScene();
  9485. var previousCamera = null;
  9486. if (scene.activeCamera !== camera) {
  9487. previousCamera = scene.activeCamera;
  9488. scene.activeCamera = camera;
  9489. }
  9490. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9491. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9492. texture.renderList = null;
  9493. texture.samples = samples;
  9494. if (antialiasing) {
  9495. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9496. }
  9497. texture.onAfterRenderObservable.add(function () {
  9498. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9499. });
  9500. scene.incrementRenderId();
  9501. scene.resetCachedMaterial();
  9502. texture.render(true);
  9503. texture.dispose();
  9504. if (previousCamera) {
  9505. scene.activeCamera = previousCamera;
  9506. }
  9507. camera.getProjectionMatrix(true); // Force cache refresh;
  9508. };
  9509. // XHR response validator for local file scenario
  9510. Tools.ValidateXHRData = function (xhr, dataType) {
  9511. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9512. if (dataType === void 0) { dataType = 7; }
  9513. try {
  9514. if (dataType & 1) {
  9515. if (xhr.responseText && xhr.responseText.length > 0) {
  9516. return true;
  9517. }
  9518. else if (dataType === 1) {
  9519. return false;
  9520. }
  9521. }
  9522. if (dataType & 2) {
  9523. // Check header width and height since there is no "TGA" magic number
  9524. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9525. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9526. return true;
  9527. }
  9528. else if (dataType === 2) {
  9529. return false;
  9530. }
  9531. }
  9532. if (dataType & 4) {
  9533. // Check for the "DDS" magic number
  9534. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9535. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9536. return true;
  9537. }
  9538. else {
  9539. return false;
  9540. }
  9541. }
  9542. }
  9543. catch (e) {
  9544. // Global protection
  9545. }
  9546. return false;
  9547. };
  9548. /**
  9549. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9550. * Be aware Math.random() could cause collisions, but:
  9551. * "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"
  9552. */
  9553. Tools.RandomId = function () {
  9554. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9555. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9556. return v.toString(16);
  9557. });
  9558. };
  9559. /**
  9560. * Test if the given uri is a base64 string.
  9561. * @param uri The uri to test
  9562. * @return True if the uri is a base64 string or false otherwise.
  9563. */
  9564. Tools.IsBase64 = function (uri) {
  9565. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9566. };
  9567. /**
  9568. * Decode the given base64 uri.
  9569. * @param uri The uri to decode
  9570. * @return The decoded base64 data.
  9571. */
  9572. Tools.DecodeBase64 = function (uri) {
  9573. var decodedString = atob(uri.split(",")[1]);
  9574. var bufferLength = decodedString.length;
  9575. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9576. for (var i = 0; i < bufferLength; i++) {
  9577. bufferView[i] = decodedString.charCodeAt(i);
  9578. }
  9579. return bufferView.buffer;
  9580. };
  9581. Object.defineProperty(Tools, "NoneLogLevel", {
  9582. get: function () {
  9583. return Tools._NoneLogLevel;
  9584. },
  9585. enumerable: true,
  9586. configurable: true
  9587. });
  9588. Object.defineProperty(Tools, "MessageLogLevel", {
  9589. get: function () {
  9590. return Tools._MessageLogLevel;
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(Tools, "WarningLogLevel", {
  9596. get: function () {
  9597. return Tools._WarningLogLevel;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(Tools, "ErrorLogLevel", {
  9603. get: function () {
  9604. return Tools._ErrorLogLevel;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(Tools, "AllLogLevel", {
  9610. get: function () {
  9611. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Tools._AddLogEntry = function (entry) {
  9617. Tools._LogCache = entry + Tools._LogCache;
  9618. if (Tools.OnNewCacheEntry) {
  9619. Tools.OnNewCacheEntry(entry);
  9620. }
  9621. };
  9622. Tools._FormatMessage = function (message) {
  9623. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9624. var date = new Date();
  9625. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9626. };
  9627. Tools._LogDisabled = function (message) {
  9628. // nothing to do
  9629. };
  9630. Tools._LogEnabled = function (message) {
  9631. var formattedMessage = Tools._FormatMessage(message);
  9632. console.log("BJS - " + formattedMessage);
  9633. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9634. Tools._AddLogEntry(entry);
  9635. };
  9636. Tools._WarnDisabled = function (message) {
  9637. // nothing to do
  9638. };
  9639. Tools._WarnEnabled = function (message) {
  9640. var formattedMessage = Tools._FormatMessage(message);
  9641. console.warn("BJS - " + formattedMessage);
  9642. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9643. Tools._AddLogEntry(entry);
  9644. };
  9645. Tools._ErrorDisabled = function (message) {
  9646. // nothing to do
  9647. };
  9648. Tools._ErrorEnabled = function (message) {
  9649. Tools.errorsCount++;
  9650. var formattedMessage = Tools._FormatMessage(message);
  9651. console.error("BJS - " + formattedMessage);
  9652. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9653. Tools._AddLogEntry(entry);
  9654. };
  9655. Object.defineProperty(Tools, "LogCache", {
  9656. get: function () {
  9657. return Tools._LogCache;
  9658. },
  9659. enumerable: true,
  9660. configurable: true
  9661. });
  9662. Tools.ClearLogCache = function () {
  9663. Tools._LogCache = "";
  9664. Tools.errorsCount = 0;
  9665. };
  9666. Object.defineProperty(Tools, "LogLevels", {
  9667. set: function (level) {
  9668. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9669. Tools.Log = Tools._LogEnabled;
  9670. }
  9671. else {
  9672. Tools.Log = Tools._LogDisabled;
  9673. }
  9674. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9675. Tools.Warn = Tools._WarnEnabled;
  9676. }
  9677. else {
  9678. Tools.Warn = Tools._WarnDisabled;
  9679. }
  9680. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9681. Tools.Error = Tools._ErrorEnabled;
  9682. }
  9683. else {
  9684. Tools.Error = Tools._ErrorDisabled;
  9685. }
  9686. },
  9687. enumerable: true,
  9688. configurable: true
  9689. });
  9690. Tools.IsWindowObjectExist = function () {
  9691. return (typeof window) !== "undefined";
  9692. };
  9693. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9694. get: function () {
  9695. return Tools._PerformanceNoneLogLevel;
  9696. },
  9697. enumerable: true,
  9698. configurable: true
  9699. });
  9700. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9701. get: function () {
  9702. return Tools._PerformanceUserMarkLogLevel;
  9703. },
  9704. enumerable: true,
  9705. configurable: true
  9706. });
  9707. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9708. get: function () {
  9709. return Tools._PerformanceConsoleLogLevel;
  9710. },
  9711. enumerable: true,
  9712. configurable: true
  9713. });
  9714. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9715. set: function (level) {
  9716. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9717. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9718. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9719. return;
  9720. }
  9721. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9722. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9723. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9724. return;
  9725. }
  9726. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9727. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9728. },
  9729. enumerable: true,
  9730. configurable: true
  9731. });
  9732. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9733. };
  9734. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9735. };
  9736. Tools._StartUserMark = function (counterName, condition) {
  9737. if (condition === void 0) { condition = true; }
  9738. if (!Tools._performance) {
  9739. if (!Tools.IsWindowObjectExist()) {
  9740. return;
  9741. }
  9742. Tools._performance = window.performance;
  9743. }
  9744. if (!condition || !Tools._performance.mark) {
  9745. return;
  9746. }
  9747. Tools._performance.mark(counterName + "-Begin");
  9748. };
  9749. Tools._EndUserMark = function (counterName, condition) {
  9750. if (condition === void 0) { condition = true; }
  9751. if (!condition || !Tools._performance.mark) {
  9752. return;
  9753. }
  9754. Tools._performance.mark(counterName + "-End");
  9755. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9756. };
  9757. Tools._StartPerformanceConsole = function (counterName, condition) {
  9758. if (condition === void 0) { condition = true; }
  9759. if (!condition) {
  9760. return;
  9761. }
  9762. Tools._StartUserMark(counterName, condition);
  9763. if (console.time) {
  9764. console.time(counterName);
  9765. }
  9766. };
  9767. Tools._EndPerformanceConsole = function (counterName, condition) {
  9768. if (condition === void 0) { condition = true; }
  9769. if (!condition) {
  9770. return;
  9771. }
  9772. Tools._EndUserMark(counterName, condition);
  9773. if (console.time) {
  9774. console.timeEnd(counterName);
  9775. }
  9776. };
  9777. Object.defineProperty(Tools, "Now", {
  9778. get: function () {
  9779. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9780. return window.performance.now();
  9781. }
  9782. return Date.now();
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. /**
  9788. * This method will return the name of the class used to create the instance of the given object.
  9789. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9790. * @param object the object to get the class name from
  9791. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9792. */
  9793. Tools.GetClassName = function (object, isType) {
  9794. if (isType === void 0) { isType = false; }
  9795. var name = null;
  9796. if (!isType && object.getClassName) {
  9797. name = object.getClassName();
  9798. }
  9799. else {
  9800. if (object instanceof Object) {
  9801. var classObj = isType ? object : Object.getPrototypeOf(object);
  9802. name = classObj.constructor["__bjsclassName__"];
  9803. }
  9804. if (!name) {
  9805. name = typeof object;
  9806. }
  9807. }
  9808. return name;
  9809. };
  9810. Tools.First = function (array, predicate) {
  9811. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9812. var el = array_1[_i];
  9813. if (predicate(el)) {
  9814. return el;
  9815. }
  9816. }
  9817. return null;
  9818. };
  9819. /**
  9820. * This method will return the name of the full name of the class, including its owning module (if any).
  9821. * 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).
  9822. * @param object the object to get the class name from
  9823. * @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.
  9824. */
  9825. Tools.getFullClassName = function (object, isType) {
  9826. if (isType === void 0) { isType = false; }
  9827. var className = null;
  9828. var moduleName = null;
  9829. if (!isType && object.getClassName) {
  9830. className = object.getClassName();
  9831. }
  9832. else {
  9833. if (object instanceof Object) {
  9834. var classObj = isType ? object : Object.getPrototypeOf(object);
  9835. className = classObj.constructor["__bjsclassName__"];
  9836. moduleName = classObj.constructor["__bjsmoduleName__"];
  9837. }
  9838. if (!className) {
  9839. className = typeof object;
  9840. }
  9841. }
  9842. if (!className) {
  9843. return null;
  9844. }
  9845. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9846. };
  9847. /**
  9848. * 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.
  9849. * @param array
  9850. */
  9851. Tools.arrayOrStringFeeder = function (array) {
  9852. return function (index) {
  9853. if (index >= array.length) {
  9854. return null;
  9855. }
  9856. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9857. if (val && val.getHashCode) {
  9858. val = val.getHashCode();
  9859. }
  9860. if (typeof val === "string") {
  9861. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9862. }
  9863. return val;
  9864. };
  9865. };
  9866. /**
  9867. * Compute the hashCode of a stream of number
  9868. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9869. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9870. * @return the hash code computed
  9871. */
  9872. Tools.hashCodeFromStream = function (feeder) {
  9873. // Based from here: http://stackoverflow.com/a/7616484/802124
  9874. var hash = 0;
  9875. var index = 0;
  9876. var chr = feeder(index++);
  9877. while (chr != null) {
  9878. hash = ((hash << 5) - hash) + chr;
  9879. hash |= 0; // Convert to 32bit integer
  9880. chr = feeder(index++);
  9881. }
  9882. return hash;
  9883. };
  9884. /**
  9885. * Returns a promise that resolves after the given amount of time.
  9886. * @param delay Number of milliseconds to delay
  9887. * @returns Promise that resolves after the given amount of time
  9888. */
  9889. Tools.DelayAsync = function (delay) {
  9890. return new Promise(function (resolve) {
  9891. setTimeout(function () {
  9892. resolve();
  9893. }, delay);
  9894. });
  9895. };
  9896. /**
  9897. * Gets the current gradient from an array of IValueGradient
  9898. * @param ratio defines the current ratio to get
  9899. * @param gradients defines the array of IValueGradient
  9900. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9901. */
  9902. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9903. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9904. var currentGradient = gradients[gradientIndex];
  9905. var nextGradient = gradients[gradientIndex + 1];
  9906. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9907. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9908. updateFunc(currentGradient, nextGradient, scale);
  9909. }
  9910. }
  9911. };
  9912. Tools.BaseUrl = "";
  9913. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9914. /**
  9915. * Default behaviour for cors in the application.
  9916. * It can be a string if the expected behavior is identical in the entire app.
  9917. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9918. */
  9919. Tools.CorsBehavior = "anonymous";
  9920. Tools.UseFallbackTexture = true;
  9921. /**
  9922. * Use this object to register external classes like custom textures or material
  9923. * to allow the laoders to instantiate them
  9924. */
  9925. Tools.RegisteredExternalClasses = {};
  9926. // Used in case of a texture loading problem
  9927. 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";
  9928. Tools._tmpFloatArray = new Float32Array(1);
  9929. Tools.PreprocessUrl = function (url) {
  9930. return url;
  9931. };
  9932. // Logs
  9933. Tools._NoneLogLevel = 0;
  9934. Tools._MessageLogLevel = 1;
  9935. Tools._WarningLogLevel = 2;
  9936. Tools._ErrorLogLevel = 4;
  9937. Tools._LogCache = "";
  9938. Tools.errorsCount = 0;
  9939. Tools.Log = Tools._LogEnabled;
  9940. Tools.Warn = Tools._WarnEnabled;
  9941. Tools.Error = Tools._ErrorEnabled;
  9942. // Performances
  9943. Tools._PerformanceNoneLogLevel = 0;
  9944. Tools._PerformanceUserMarkLogLevel = 1;
  9945. Tools._PerformanceConsoleLogLevel = 2;
  9946. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9947. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9948. return Tools;
  9949. }());
  9950. BABYLON.Tools = Tools;
  9951. /**
  9952. * This class is used to track a performance counter which is number based.
  9953. * The user has access to many properties which give statistics of different nature
  9954. *
  9955. * The implementer can track two kinds of Performance Counter: time and count
  9956. * 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.
  9957. * 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.
  9958. */
  9959. var PerfCounter = /** @class */ (function () {
  9960. function PerfCounter() {
  9961. this._startMonitoringTime = 0;
  9962. this._min = 0;
  9963. this._max = 0;
  9964. this._average = 0;
  9965. this._lastSecAverage = 0;
  9966. this._current = 0;
  9967. this._totalValueCount = 0;
  9968. this._totalAccumulated = 0;
  9969. this._lastSecAccumulated = 0;
  9970. this._lastSecTime = 0;
  9971. this._lastSecValueCount = 0;
  9972. }
  9973. Object.defineProperty(PerfCounter.prototype, "min", {
  9974. /**
  9975. * Returns the smallest value ever
  9976. */
  9977. get: function () {
  9978. return this._min;
  9979. },
  9980. enumerable: true,
  9981. configurable: true
  9982. });
  9983. Object.defineProperty(PerfCounter.prototype, "max", {
  9984. /**
  9985. * Returns the biggest value ever
  9986. */
  9987. get: function () {
  9988. return this._max;
  9989. },
  9990. enumerable: true,
  9991. configurable: true
  9992. });
  9993. Object.defineProperty(PerfCounter.prototype, "average", {
  9994. /**
  9995. * Returns the average value since the performance counter is running
  9996. */
  9997. get: function () {
  9998. return this._average;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10004. /**
  10005. * Returns the average value of the last second the counter was monitored
  10006. */
  10007. get: function () {
  10008. return this._lastSecAverage;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(PerfCounter.prototype, "current", {
  10014. /**
  10015. * Returns the current value
  10016. */
  10017. get: function () {
  10018. return this._current;
  10019. },
  10020. enumerable: true,
  10021. configurable: true
  10022. });
  10023. Object.defineProperty(PerfCounter.prototype, "total", {
  10024. get: function () {
  10025. return this._totalAccumulated;
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. Object.defineProperty(PerfCounter.prototype, "count", {
  10031. get: function () {
  10032. return this._totalValueCount;
  10033. },
  10034. enumerable: true,
  10035. configurable: true
  10036. });
  10037. /**
  10038. * Call this method to start monitoring a new frame.
  10039. * 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.
  10040. */
  10041. PerfCounter.prototype.fetchNewFrame = function () {
  10042. this._totalValueCount++;
  10043. this._current = 0;
  10044. this._lastSecValueCount++;
  10045. };
  10046. /**
  10047. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10048. * @param newCount the count value to add to the monitored count
  10049. * @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.
  10050. */
  10051. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10052. if (!PerfCounter.Enabled) {
  10053. return;
  10054. }
  10055. this._current += newCount;
  10056. if (fetchResult) {
  10057. this._fetchResult();
  10058. }
  10059. };
  10060. /**
  10061. * Start monitoring this performance counter
  10062. */
  10063. PerfCounter.prototype.beginMonitoring = function () {
  10064. if (!PerfCounter.Enabled) {
  10065. return;
  10066. }
  10067. this._startMonitoringTime = Tools.Now;
  10068. };
  10069. /**
  10070. * Compute the time lapsed since the previous beginMonitoring() call.
  10071. * @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
  10072. */
  10073. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10074. if (newFrame === void 0) { newFrame = true; }
  10075. if (!PerfCounter.Enabled) {
  10076. return;
  10077. }
  10078. if (newFrame) {
  10079. this.fetchNewFrame();
  10080. }
  10081. var currentTime = Tools.Now;
  10082. this._current = currentTime - this._startMonitoringTime;
  10083. if (newFrame) {
  10084. this._fetchResult();
  10085. }
  10086. };
  10087. PerfCounter.prototype._fetchResult = function () {
  10088. this._totalAccumulated += this._current;
  10089. this._lastSecAccumulated += this._current;
  10090. // Min/Max update
  10091. this._min = Math.min(this._min, this._current);
  10092. this._max = Math.max(this._max, this._current);
  10093. this._average = this._totalAccumulated / this._totalValueCount;
  10094. // Reset last sec?
  10095. var now = Tools.Now;
  10096. if ((now - this._lastSecTime) > 1000) {
  10097. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10098. this._lastSecTime = now;
  10099. this._lastSecAccumulated = 0;
  10100. this._lastSecValueCount = 0;
  10101. }
  10102. };
  10103. PerfCounter.Enabled = true;
  10104. return PerfCounter;
  10105. }());
  10106. BABYLON.PerfCounter = PerfCounter;
  10107. /**
  10108. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10109. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10110. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10111. * @param name The name of the class, case should be preserved
  10112. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10113. */
  10114. function className(name, module) {
  10115. return function (target) {
  10116. target["__bjsclassName__"] = name;
  10117. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10118. };
  10119. }
  10120. BABYLON.className = className;
  10121. /**
  10122. * An implementation of a loop for asynchronous functions.
  10123. */
  10124. var AsyncLoop = /** @class */ (function () {
  10125. /**
  10126. * Constroctor.
  10127. * @param iterations the number of iterations.
  10128. * @param _fn the function to run each iteration
  10129. * @param _successCallback the callback that will be called upon succesful execution
  10130. * @param offset starting offset.
  10131. */
  10132. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10133. if (offset === void 0) { offset = 0; }
  10134. this.iterations = iterations;
  10135. this._fn = _fn;
  10136. this._successCallback = _successCallback;
  10137. this.index = offset - 1;
  10138. this._done = false;
  10139. }
  10140. /**
  10141. * Execute the next iteration. Must be called after the last iteration was finished.
  10142. */
  10143. AsyncLoop.prototype.executeNext = function () {
  10144. if (!this._done) {
  10145. if (this.index + 1 < this.iterations) {
  10146. ++this.index;
  10147. this._fn(this);
  10148. }
  10149. else {
  10150. this.breakLoop();
  10151. }
  10152. }
  10153. };
  10154. /**
  10155. * Break the loop and run the success callback.
  10156. */
  10157. AsyncLoop.prototype.breakLoop = function () {
  10158. this._done = true;
  10159. this._successCallback();
  10160. };
  10161. /**
  10162. * Helper function
  10163. */
  10164. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10165. if (offset === void 0) { offset = 0; }
  10166. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10167. loop.executeNext();
  10168. return loop;
  10169. };
  10170. /**
  10171. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10172. * @param iterations total number of iterations
  10173. * @param syncedIterations number of synchronous iterations in each async iteration.
  10174. * @param fn the function to call each iteration.
  10175. * @param callback a success call back that will be called when iterating stops.
  10176. * @param breakFunction a break condition (optional)
  10177. * @param timeout timeout settings for the setTimeout function. default - 0.
  10178. * @constructor
  10179. */
  10180. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10181. if (timeout === void 0) { timeout = 0; }
  10182. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10183. if (breakFunction && breakFunction())
  10184. loop.breakLoop();
  10185. else {
  10186. setTimeout(function () {
  10187. for (var i = 0; i < syncedIterations; ++i) {
  10188. var iteration = (loop.index * syncedIterations) + i;
  10189. if (iteration >= iterations)
  10190. break;
  10191. fn(iteration);
  10192. if (breakFunction && breakFunction()) {
  10193. loop.breakLoop();
  10194. break;
  10195. }
  10196. }
  10197. loop.executeNext();
  10198. }, timeout);
  10199. }
  10200. }, callback);
  10201. };
  10202. return AsyncLoop;
  10203. }());
  10204. BABYLON.AsyncLoop = AsyncLoop;
  10205. })(BABYLON || (BABYLON = {}));
  10206. //# sourceMappingURL=babylon.tools.js.map
  10207. var BABYLON;
  10208. (function (BABYLON) {
  10209. var PromiseStates;
  10210. (function (PromiseStates) {
  10211. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10212. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10213. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10214. })(PromiseStates || (PromiseStates = {}));
  10215. var FulFillmentAgregator = /** @class */ (function () {
  10216. function FulFillmentAgregator() {
  10217. this.count = 0;
  10218. this.target = 0;
  10219. this.results = [];
  10220. }
  10221. return FulFillmentAgregator;
  10222. }());
  10223. var InternalPromise = /** @class */ (function () {
  10224. function InternalPromise(resolver) {
  10225. var _this = this;
  10226. this._state = PromiseStates.Pending;
  10227. this._children = new Array();
  10228. this._rejectWasConsumed = false;
  10229. if (!resolver) {
  10230. return;
  10231. }
  10232. try {
  10233. resolver(function (value) {
  10234. _this._resolve(value);
  10235. }, function (reason) {
  10236. _this._reject(reason);
  10237. });
  10238. }
  10239. catch (e) {
  10240. this._reject(e);
  10241. }
  10242. }
  10243. Object.defineProperty(InternalPromise.prototype, "_result", {
  10244. get: function () {
  10245. return this._resultValue;
  10246. },
  10247. set: function (value) {
  10248. this._resultValue = value;
  10249. if (this._parent && this._parent._result === undefined) {
  10250. this._parent._result = value;
  10251. }
  10252. },
  10253. enumerable: true,
  10254. configurable: true
  10255. });
  10256. InternalPromise.prototype.catch = function (onRejected) {
  10257. return this.then(undefined, onRejected);
  10258. };
  10259. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10260. var _this = this;
  10261. var newPromise = new InternalPromise();
  10262. newPromise._onFulfilled = onFulfilled;
  10263. newPromise._onRejected = onRejected;
  10264. // Composition
  10265. this._children.push(newPromise);
  10266. newPromise._parent = this;
  10267. if (this._state !== PromiseStates.Pending) {
  10268. BABYLON.Tools.SetImmediate(function () {
  10269. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10270. var returnedValue = newPromise._resolve(_this._result);
  10271. if (returnedValue !== undefined && returnedValue !== null) {
  10272. if (returnedValue._state !== undefined) {
  10273. var returnedPromise = returnedValue;
  10274. newPromise._children.push(returnedPromise);
  10275. returnedPromise._parent = newPromise;
  10276. newPromise = returnedPromise;
  10277. }
  10278. else {
  10279. newPromise._result = returnedValue;
  10280. }
  10281. }
  10282. }
  10283. else {
  10284. newPromise._reject(_this._reason);
  10285. }
  10286. });
  10287. }
  10288. return newPromise;
  10289. };
  10290. InternalPromise.prototype._moveChildren = function (children) {
  10291. var _this = this;
  10292. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10293. this._children.forEach(function (child) {
  10294. child._parent = _this;
  10295. });
  10296. if (this._state === PromiseStates.Fulfilled) {
  10297. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10298. var child = _b[_i];
  10299. child._resolve(this._result);
  10300. }
  10301. }
  10302. else if (this._state === PromiseStates.Rejected) {
  10303. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10304. var child = _d[_c];
  10305. child._reject(this._reason);
  10306. }
  10307. }
  10308. var _a;
  10309. };
  10310. InternalPromise.prototype._resolve = function (value) {
  10311. try {
  10312. this._state = PromiseStates.Fulfilled;
  10313. var returnedValue = null;
  10314. if (this._onFulfilled) {
  10315. returnedValue = this._onFulfilled(value);
  10316. }
  10317. if (returnedValue !== undefined && returnedValue !== null) {
  10318. if (returnedValue._state !== undefined) {
  10319. // Transmit children
  10320. var returnedPromise = returnedValue;
  10321. returnedPromise._parent = this;
  10322. returnedPromise._moveChildren(this._children);
  10323. value = returnedPromise._result;
  10324. }
  10325. else {
  10326. value = returnedValue;
  10327. }
  10328. }
  10329. this._result = value;
  10330. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10331. var child = _a[_i];
  10332. child._resolve(value);
  10333. }
  10334. this._children.length = 0;
  10335. delete this._onFulfilled;
  10336. delete this._onRejected;
  10337. }
  10338. catch (e) {
  10339. this._reject(e, true);
  10340. }
  10341. };
  10342. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10343. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10344. this._state = PromiseStates.Rejected;
  10345. this._reason = reason;
  10346. if (this._onRejected && !onLocalThrow) {
  10347. try {
  10348. this._onRejected(reason);
  10349. this._rejectWasConsumed = true;
  10350. }
  10351. catch (e) {
  10352. reason = e;
  10353. }
  10354. }
  10355. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10356. var child = _a[_i];
  10357. if (this._rejectWasConsumed) {
  10358. child._resolve(null);
  10359. }
  10360. else {
  10361. child._reject(reason);
  10362. }
  10363. }
  10364. this._children.length = 0;
  10365. delete this._onFulfilled;
  10366. delete this._onRejected;
  10367. };
  10368. InternalPromise.resolve = function (value) {
  10369. var newPromise = new InternalPromise();
  10370. newPromise._resolve(value);
  10371. return newPromise;
  10372. };
  10373. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10374. promise.then(function (value) {
  10375. agregator.results[index] = value;
  10376. agregator.count++;
  10377. if (agregator.count === agregator.target) {
  10378. agregator.rootPromise._resolve(agregator.results);
  10379. }
  10380. return null;
  10381. }, function (reason) {
  10382. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10383. agregator.rootPromise._reject(reason);
  10384. }
  10385. });
  10386. };
  10387. InternalPromise.all = function (promises) {
  10388. var newPromise = new InternalPromise();
  10389. var agregator = new FulFillmentAgregator();
  10390. agregator.target = promises.length;
  10391. agregator.rootPromise = newPromise;
  10392. if (promises.length) {
  10393. for (var index = 0; index < promises.length; index++) {
  10394. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10395. }
  10396. }
  10397. else {
  10398. newPromise._resolve([]);
  10399. }
  10400. return newPromise;
  10401. };
  10402. InternalPromise.race = function (promises) {
  10403. var newPromise = new InternalPromise();
  10404. if (promises.length) {
  10405. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10406. var promise = promises_1[_i];
  10407. promise.then(function (value) {
  10408. if (newPromise) {
  10409. newPromise._resolve(value);
  10410. newPromise = null;
  10411. }
  10412. return null;
  10413. }, function (reason) {
  10414. if (newPromise) {
  10415. newPromise._reject(reason);
  10416. newPromise = null;
  10417. }
  10418. });
  10419. }
  10420. }
  10421. return newPromise;
  10422. };
  10423. return InternalPromise;
  10424. }());
  10425. /**
  10426. * Helper class that provides a small promise polyfill
  10427. */
  10428. var PromisePolyfill = /** @class */ (function () {
  10429. function PromisePolyfill() {
  10430. }
  10431. /**
  10432. * Static function used to check if the polyfill is required
  10433. * If this is the case then the function will inject the polyfill to window.Promise
  10434. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10435. */
  10436. PromisePolyfill.Apply = function (force) {
  10437. if (force === void 0) { force = false; }
  10438. if (force || typeof Promise === 'undefined') {
  10439. var root = window;
  10440. root.Promise = InternalPromise;
  10441. }
  10442. };
  10443. return PromisePolyfill;
  10444. }());
  10445. BABYLON.PromisePolyfill = PromisePolyfill;
  10446. })(BABYLON || (BABYLON = {}));
  10447. //# sourceMappingURL=babylon.promise.js.map
  10448. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10449. var BABYLON;
  10450. (function (BABYLON) {
  10451. /**
  10452. * Helper class to push actions to a pool of workers.
  10453. */
  10454. var WorkerPool = /** @class */ (function () {
  10455. /**
  10456. * Constructor
  10457. * @param workers Array of workers to use for actions
  10458. */
  10459. function WorkerPool(workers) {
  10460. this._pendingActions = new Array();
  10461. this._workerInfos = workers.map(function (worker) { return ({
  10462. worker: worker,
  10463. active: false
  10464. }); });
  10465. }
  10466. /**
  10467. * Terminates all workers and clears any pending actions.
  10468. */
  10469. WorkerPool.prototype.dispose = function () {
  10470. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10471. var workerInfo = _a[_i];
  10472. workerInfo.worker.terminate();
  10473. }
  10474. delete this._workerInfos;
  10475. delete this._pendingActions;
  10476. };
  10477. /**
  10478. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10479. * pended until a worker has completed its action.
  10480. * @param action The action to perform. Call onComplete when the action is complete.
  10481. */
  10482. WorkerPool.prototype.push = function (action) {
  10483. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10484. var workerInfo = _a[_i];
  10485. if (!workerInfo.active) {
  10486. this._execute(workerInfo, action);
  10487. return;
  10488. }
  10489. }
  10490. this._pendingActions.push(action);
  10491. };
  10492. WorkerPool.prototype._execute = function (workerInfo, action) {
  10493. var _this = this;
  10494. workerInfo.active = true;
  10495. action(workerInfo.worker, function () {
  10496. workerInfo.active = false;
  10497. var nextAction = _this._pendingActions.shift();
  10498. if (nextAction) {
  10499. _this._execute(workerInfo, nextAction);
  10500. }
  10501. });
  10502. };
  10503. return WorkerPool;
  10504. }());
  10505. BABYLON.WorkerPool = WorkerPool;
  10506. })(BABYLON || (BABYLON = {}));
  10507. //# sourceMappingURL=babylon.workerPool.js.map
  10508. var BABYLON;
  10509. (function (BABYLON) {
  10510. /**
  10511. * @hidden
  10512. **/
  10513. var _AlphaState = /** @class */ (function () {
  10514. /**
  10515. * Initializes the state.
  10516. */
  10517. function _AlphaState() {
  10518. this._isAlphaBlendDirty = false;
  10519. this._isBlendFunctionParametersDirty = false;
  10520. this._isBlendEquationParametersDirty = false;
  10521. this._isBlendConstantsDirty = false;
  10522. this._alphaBlend = false;
  10523. this._blendFunctionParameters = new Array(4);
  10524. this._blendEquationParameters = new Array(2);
  10525. this._blendConstants = new Array(4);
  10526. this.reset();
  10527. }
  10528. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10529. get: function () {
  10530. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10531. },
  10532. enumerable: true,
  10533. configurable: true
  10534. });
  10535. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10536. get: function () {
  10537. return this._alphaBlend;
  10538. },
  10539. set: function (value) {
  10540. if (this._alphaBlend === value) {
  10541. return;
  10542. }
  10543. this._alphaBlend = value;
  10544. this._isAlphaBlendDirty = true;
  10545. },
  10546. enumerable: true,
  10547. configurable: true
  10548. });
  10549. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10550. if (this._blendConstants[0] === r &&
  10551. this._blendConstants[1] === g &&
  10552. this._blendConstants[2] === b &&
  10553. this._blendConstants[3] === a) {
  10554. return;
  10555. }
  10556. this._blendConstants[0] = r;
  10557. this._blendConstants[1] = g;
  10558. this._blendConstants[2] = b;
  10559. this._blendConstants[3] = a;
  10560. this._isBlendConstantsDirty = true;
  10561. };
  10562. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10563. if (this._blendFunctionParameters[0] === value0 &&
  10564. this._blendFunctionParameters[1] === value1 &&
  10565. this._blendFunctionParameters[2] === value2 &&
  10566. this._blendFunctionParameters[3] === value3) {
  10567. return;
  10568. }
  10569. this._blendFunctionParameters[0] = value0;
  10570. this._blendFunctionParameters[1] = value1;
  10571. this._blendFunctionParameters[2] = value2;
  10572. this._blendFunctionParameters[3] = value3;
  10573. this._isBlendFunctionParametersDirty = true;
  10574. };
  10575. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10576. if (this._blendEquationParameters[0] === rgb &&
  10577. this._blendEquationParameters[1] === alpha) {
  10578. return;
  10579. }
  10580. this._blendEquationParameters[0] = rgb;
  10581. this._blendEquationParameters[1] = alpha;
  10582. this._isBlendEquationParametersDirty = true;
  10583. };
  10584. _AlphaState.prototype.reset = function () {
  10585. this._alphaBlend = false;
  10586. this._blendFunctionParameters[0] = null;
  10587. this._blendFunctionParameters[1] = null;
  10588. this._blendFunctionParameters[2] = null;
  10589. this._blendFunctionParameters[3] = null;
  10590. this._blendEquationParameters[0] = null;
  10591. this._blendEquationParameters[1] = null;
  10592. this._blendConstants[0] = null;
  10593. this._blendConstants[1] = null;
  10594. this._blendConstants[2] = null;
  10595. this._blendConstants[3] = null;
  10596. this._isAlphaBlendDirty = true;
  10597. this._isBlendFunctionParametersDirty = false;
  10598. this._isBlendEquationParametersDirty = false;
  10599. this._isBlendConstantsDirty = false;
  10600. };
  10601. _AlphaState.prototype.apply = function (gl) {
  10602. if (!this.isDirty) {
  10603. return;
  10604. }
  10605. // Alpha blend
  10606. if (this._isAlphaBlendDirty) {
  10607. if (this._alphaBlend) {
  10608. gl.enable(gl.BLEND);
  10609. }
  10610. else {
  10611. gl.disable(gl.BLEND);
  10612. }
  10613. this._isAlphaBlendDirty = false;
  10614. }
  10615. // Alpha function
  10616. if (this._isBlendFunctionParametersDirty) {
  10617. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10618. this._isBlendFunctionParametersDirty = false;
  10619. }
  10620. // Alpha equation
  10621. if (this._isBlendEquationParametersDirty) {
  10622. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10623. this._isBlendEquationParametersDirty = false;
  10624. }
  10625. // Constants
  10626. if (this._isBlendConstantsDirty) {
  10627. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10628. this._isBlendConstantsDirty = false;
  10629. }
  10630. };
  10631. return _AlphaState;
  10632. }());
  10633. BABYLON._AlphaState = _AlphaState;
  10634. })(BABYLON || (BABYLON = {}));
  10635. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10636. var BABYLON;
  10637. (function (BABYLON) {
  10638. /**
  10639. * @hidden
  10640. **/
  10641. var _DepthCullingState = /** @class */ (function () {
  10642. /**
  10643. * Initializes the state.
  10644. */
  10645. function _DepthCullingState() {
  10646. this._isDepthTestDirty = false;
  10647. this._isDepthMaskDirty = false;
  10648. this._isDepthFuncDirty = false;
  10649. this._isCullFaceDirty = false;
  10650. this._isCullDirty = false;
  10651. this._isZOffsetDirty = false;
  10652. this._isFrontFaceDirty = false;
  10653. this.reset();
  10654. }
  10655. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10656. get: function () {
  10657. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10663. get: function () {
  10664. return this._zOffset;
  10665. },
  10666. set: function (value) {
  10667. if (this._zOffset === value) {
  10668. return;
  10669. }
  10670. this._zOffset = value;
  10671. this._isZOffsetDirty = true;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10677. get: function () {
  10678. return this._cullFace;
  10679. },
  10680. set: function (value) {
  10681. if (this._cullFace === value) {
  10682. return;
  10683. }
  10684. this._cullFace = value;
  10685. this._isCullFaceDirty = true;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10691. get: function () {
  10692. return this._cull;
  10693. },
  10694. set: function (value) {
  10695. if (this._cull === value) {
  10696. return;
  10697. }
  10698. this._cull = value;
  10699. this._isCullDirty = true;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10705. get: function () {
  10706. return this._depthFunc;
  10707. },
  10708. set: function (value) {
  10709. if (this._depthFunc === value) {
  10710. return;
  10711. }
  10712. this._depthFunc = value;
  10713. this._isDepthFuncDirty = true;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10719. get: function () {
  10720. return this._depthMask;
  10721. },
  10722. set: function (value) {
  10723. if (this._depthMask === value) {
  10724. return;
  10725. }
  10726. this._depthMask = value;
  10727. this._isDepthMaskDirty = true;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10733. get: function () {
  10734. return this._depthTest;
  10735. },
  10736. set: function (value) {
  10737. if (this._depthTest === value) {
  10738. return;
  10739. }
  10740. this._depthTest = value;
  10741. this._isDepthTestDirty = true;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10747. get: function () {
  10748. return this._frontFace;
  10749. },
  10750. set: function (value) {
  10751. if (this._frontFace === value) {
  10752. return;
  10753. }
  10754. this._frontFace = value;
  10755. this._isFrontFaceDirty = true;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. _DepthCullingState.prototype.reset = function () {
  10761. this._depthMask = true;
  10762. this._depthTest = true;
  10763. this._depthFunc = null;
  10764. this._cullFace = null;
  10765. this._cull = null;
  10766. this._zOffset = 0;
  10767. this._frontFace = null;
  10768. this._isDepthTestDirty = true;
  10769. this._isDepthMaskDirty = true;
  10770. this._isDepthFuncDirty = false;
  10771. this._isCullFaceDirty = false;
  10772. this._isCullDirty = false;
  10773. this._isZOffsetDirty = false;
  10774. this._isFrontFaceDirty = false;
  10775. };
  10776. _DepthCullingState.prototype.apply = function (gl) {
  10777. if (!this.isDirty) {
  10778. return;
  10779. }
  10780. // Cull
  10781. if (this._isCullDirty) {
  10782. if (this.cull) {
  10783. gl.enable(gl.CULL_FACE);
  10784. }
  10785. else {
  10786. gl.disable(gl.CULL_FACE);
  10787. }
  10788. this._isCullDirty = false;
  10789. }
  10790. // Cull face
  10791. if (this._isCullFaceDirty) {
  10792. gl.cullFace(this.cullFace);
  10793. this._isCullFaceDirty = false;
  10794. }
  10795. // Depth mask
  10796. if (this._isDepthMaskDirty) {
  10797. gl.depthMask(this.depthMask);
  10798. this._isDepthMaskDirty = false;
  10799. }
  10800. // Depth test
  10801. if (this._isDepthTestDirty) {
  10802. if (this.depthTest) {
  10803. gl.enable(gl.DEPTH_TEST);
  10804. }
  10805. else {
  10806. gl.disable(gl.DEPTH_TEST);
  10807. }
  10808. this._isDepthTestDirty = false;
  10809. }
  10810. // Depth func
  10811. if (this._isDepthFuncDirty) {
  10812. gl.depthFunc(this.depthFunc);
  10813. this._isDepthFuncDirty = false;
  10814. }
  10815. // zOffset
  10816. if (this._isZOffsetDirty) {
  10817. if (this.zOffset) {
  10818. gl.enable(gl.POLYGON_OFFSET_FILL);
  10819. gl.polygonOffset(this.zOffset, 0);
  10820. }
  10821. else {
  10822. gl.disable(gl.POLYGON_OFFSET_FILL);
  10823. }
  10824. this._isZOffsetDirty = false;
  10825. }
  10826. // Front face
  10827. if (this._isFrontFaceDirty) {
  10828. gl.frontFace(this.frontFace);
  10829. this._isFrontFaceDirty = false;
  10830. }
  10831. };
  10832. return _DepthCullingState;
  10833. }());
  10834. BABYLON._DepthCullingState = _DepthCullingState;
  10835. })(BABYLON || (BABYLON = {}));
  10836. //# sourceMappingURL=babylon.depthCullingState.js.map
  10837. var BABYLON;
  10838. (function (BABYLON) {
  10839. /**
  10840. * @hidden
  10841. **/
  10842. var _StencilState = /** @class */ (function () {
  10843. function _StencilState() {
  10844. this._isStencilTestDirty = false;
  10845. this._isStencilMaskDirty = false;
  10846. this._isStencilFuncDirty = false;
  10847. this._isStencilOpDirty = false;
  10848. this.reset();
  10849. }
  10850. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10851. get: function () {
  10852. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10858. get: function () {
  10859. return this._stencilFunc;
  10860. },
  10861. set: function (value) {
  10862. if (this._stencilFunc === value) {
  10863. return;
  10864. }
  10865. this._stencilFunc = value;
  10866. this._isStencilFuncDirty = true;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10872. get: function () {
  10873. return this._stencilFuncRef;
  10874. },
  10875. set: function (value) {
  10876. if (this._stencilFuncRef === value) {
  10877. return;
  10878. }
  10879. this._stencilFuncRef = value;
  10880. this._isStencilFuncDirty = true;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10886. get: function () {
  10887. return this._stencilFuncMask;
  10888. },
  10889. set: function (value) {
  10890. if (this._stencilFuncMask === value) {
  10891. return;
  10892. }
  10893. this._stencilFuncMask = value;
  10894. this._isStencilFuncDirty = true;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10900. get: function () {
  10901. return this._stencilOpStencilFail;
  10902. },
  10903. set: function (value) {
  10904. if (this._stencilOpStencilFail === value) {
  10905. return;
  10906. }
  10907. this._stencilOpStencilFail = value;
  10908. this._isStencilOpDirty = true;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10914. get: function () {
  10915. return this._stencilOpDepthFail;
  10916. },
  10917. set: function (value) {
  10918. if (this._stencilOpDepthFail === value) {
  10919. return;
  10920. }
  10921. this._stencilOpDepthFail = value;
  10922. this._isStencilOpDirty = true;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10928. get: function () {
  10929. return this._stencilOpStencilDepthPass;
  10930. },
  10931. set: function (value) {
  10932. if (this._stencilOpStencilDepthPass === value) {
  10933. return;
  10934. }
  10935. this._stencilOpStencilDepthPass = value;
  10936. this._isStencilOpDirty = true;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10942. get: function () {
  10943. return this._stencilMask;
  10944. },
  10945. set: function (value) {
  10946. if (this._stencilMask === value) {
  10947. return;
  10948. }
  10949. this._stencilMask = value;
  10950. this._isStencilMaskDirty = true;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10956. get: function () {
  10957. return this._stencilTest;
  10958. },
  10959. set: function (value) {
  10960. if (this._stencilTest === value) {
  10961. return;
  10962. }
  10963. this._stencilTest = value;
  10964. this._isStencilTestDirty = true;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. _StencilState.prototype.reset = function () {
  10970. this._stencilTest = false;
  10971. this._stencilMask = 0xFF;
  10972. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10973. this._stencilFuncRef = 1;
  10974. this._stencilFuncMask = 0xFF;
  10975. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10976. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10977. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10978. this._isStencilTestDirty = true;
  10979. this._isStencilMaskDirty = true;
  10980. this._isStencilFuncDirty = true;
  10981. this._isStencilOpDirty = true;
  10982. };
  10983. _StencilState.prototype.apply = function (gl) {
  10984. if (!this.isDirty) {
  10985. return;
  10986. }
  10987. // Stencil test
  10988. if (this._isStencilTestDirty) {
  10989. if (this.stencilTest) {
  10990. gl.enable(gl.STENCIL_TEST);
  10991. }
  10992. else {
  10993. gl.disable(gl.STENCIL_TEST);
  10994. }
  10995. this._isStencilTestDirty = false;
  10996. }
  10997. // Stencil mask
  10998. if (this._isStencilMaskDirty) {
  10999. gl.stencilMask(this.stencilMask);
  11000. this._isStencilMaskDirty = false;
  11001. }
  11002. // Stencil func
  11003. if (this._isStencilFuncDirty) {
  11004. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11005. this._isStencilFuncDirty = false;
  11006. }
  11007. // Stencil op
  11008. if (this._isStencilOpDirty) {
  11009. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11010. this._isStencilOpDirty = false;
  11011. }
  11012. };
  11013. return _StencilState;
  11014. }());
  11015. BABYLON._StencilState = _StencilState;
  11016. })(BABYLON || (BABYLON = {}));
  11017. //# sourceMappingURL=babylon.stencilState.js.map
  11018. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11019. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11020. s = arguments[i];
  11021. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11022. t[p] = s[p];
  11023. }
  11024. return t;
  11025. };
  11026. var BABYLON;
  11027. (function (BABYLON) {
  11028. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11029. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11030. };
  11031. var compileRawShader = function (gl, source, type) {
  11032. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11033. gl.shaderSource(shader, source);
  11034. gl.compileShader(shader);
  11035. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11036. var log = gl.getShaderInfoLog(shader);
  11037. if (log) {
  11038. throw new Error(log);
  11039. }
  11040. }
  11041. if (!shader) {
  11042. throw new Error("Something went wrong while compile the shader.");
  11043. }
  11044. return shader;
  11045. };
  11046. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11047. var magFilter = gl.NEAREST;
  11048. var minFilter = gl.NEAREST;
  11049. switch (samplingMode) {
  11050. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11051. magFilter = gl.LINEAR;
  11052. if (generateMipMaps) {
  11053. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11054. }
  11055. else {
  11056. minFilter = gl.LINEAR;
  11057. }
  11058. break;
  11059. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11060. magFilter = gl.LINEAR;
  11061. if (generateMipMaps) {
  11062. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11063. }
  11064. else {
  11065. minFilter = gl.LINEAR;
  11066. }
  11067. break;
  11068. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11069. magFilter = gl.NEAREST;
  11070. if (generateMipMaps) {
  11071. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11072. }
  11073. else {
  11074. minFilter = gl.NEAREST;
  11075. }
  11076. break;
  11077. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11078. magFilter = gl.NEAREST;
  11079. if (generateMipMaps) {
  11080. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11081. }
  11082. else {
  11083. minFilter = gl.NEAREST;
  11084. }
  11085. break;
  11086. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11087. magFilter = gl.NEAREST;
  11088. if (generateMipMaps) {
  11089. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11090. }
  11091. else {
  11092. minFilter = gl.LINEAR;
  11093. }
  11094. break;
  11095. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11096. magFilter = gl.NEAREST;
  11097. if (generateMipMaps) {
  11098. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11099. }
  11100. else {
  11101. minFilter = gl.LINEAR;
  11102. }
  11103. break;
  11104. case BABYLON.Texture.NEAREST_LINEAR:
  11105. magFilter = gl.NEAREST;
  11106. minFilter = gl.LINEAR;
  11107. break;
  11108. case BABYLON.Texture.NEAREST_NEAREST:
  11109. magFilter = gl.NEAREST;
  11110. minFilter = gl.NEAREST;
  11111. break;
  11112. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11113. magFilter = gl.LINEAR;
  11114. if (generateMipMaps) {
  11115. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11116. }
  11117. else {
  11118. minFilter = gl.NEAREST;
  11119. }
  11120. break;
  11121. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11122. magFilter = gl.LINEAR;
  11123. if (generateMipMaps) {
  11124. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11125. }
  11126. else {
  11127. minFilter = gl.NEAREST;
  11128. }
  11129. break;
  11130. case BABYLON.Texture.LINEAR_LINEAR:
  11131. magFilter = gl.LINEAR;
  11132. minFilter = gl.LINEAR;
  11133. break;
  11134. case BABYLON.Texture.LINEAR_NEAREST:
  11135. magFilter = gl.LINEAR;
  11136. minFilter = gl.NEAREST;
  11137. break;
  11138. }
  11139. return {
  11140. min: minFilter,
  11141. mag: magFilter
  11142. };
  11143. };
  11144. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11145. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11146. var img;
  11147. var onload = function () {
  11148. loadedImages[index] = img;
  11149. loadedImages._internalCount++;
  11150. if (scene) {
  11151. scene._removePendingData(img);
  11152. }
  11153. if (loadedImages._internalCount === 6) {
  11154. onfinish(loadedImages);
  11155. }
  11156. };
  11157. var onerror = function (message, exception) {
  11158. if (scene) {
  11159. scene._removePendingData(img);
  11160. }
  11161. if (onErrorCallBack) {
  11162. onErrorCallBack(message, exception);
  11163. }
  11164. };
  11165. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11166. if (scene) {
  11167. scene._addPendingData(img);
  11168. }
  11169. };
  11170. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11171. if (onError === void 0) { onError = null; }
  11172. var loadedImages = [];
  11173. loadedImages._internalCount = 0;
  11174. for (var index = 0; index < 6; index++) {
  11175. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11176. }
  11177. };
  11178. var BufferPointer = /** @class */ (function () {
  11179. function BufferPointer() {
  11180. }
  11181. return BufferPointer;
  11182. }());
  11183. /**
  11184. * Interface for attribute information associated with buffer instanciation
  11185. */
  11186. var InstancingAttributeInfo = /** @class */ (function () {
  11187. function InstancingAttributeInfo() {
  11188. }
  11189. return InstancingAttributeInfo;
  11190. }());
  11191. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11192. /**
  11193. * Define options used to create a render target texture
  11194. */
  11195. var RenderTargetCreationOptions = /** @class */ (function () {
  11196. function RenderTargetCreationOptions() {
  11197. }
  11198. return RenderTargetCreationOptions;
  11199. }());
  11200. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11201. /**
  11202. * Define options used to create a depth texture
  11203. */
  11204. var DepthTextureCreationOptions = /** @class */ (function () {
  11205. function DepthTextureCreationOptions() {
  11206. }
  11207. return DepthTextureCreationOptions;
  11208. }());
  11209. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11210. /**
  11211. * Class used to describe the capabilities of the engine relatively to the current browser
  11212. */
  11213. var EngineCapabilities = /** @class */ (function () {
  11214. function EngineCapabilities() {
  11215. }
  11216. return EngineCapabilities;
  11217. }());
  11218. BABYLON.EngineCapabilities = EngineCapabilities;
  11219. /**
  11220. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11221. */
  11222. var Engine = /** @class */ (function () {
  11223. /**
  11224. * Creates a new engine
  11225. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11226. * @param antialias defines enable antialiasing (default: false)
  11227. * @param options defines further options to be sent to the getContext() function
  11228. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11229. */
  11230. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11231. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11232. var _this = this;
  11233. // Public members
  11234. /**
  11235. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11236. */
  11237. this.forcePOTTextures = false;
  11238. /**
  11239. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11240. */
  11241. this.isFullscreen = false;
  11242. /**
  11243. * Gets a boolean indicating if the pointer is currently locked
  11244. */
  11245. this.isPointerLock = false;
  11246. /**
  11247. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11248. */
  11249. this.cullBackFaces = true;
  11250. /**
  11251. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11252. */
  11253. this.renderEvenInBackground = true;
  11254. /**
  11255. * Gets or sets a boolean indicating that cache can be kept between frames
  11256. */
  11257. this.preventCacheWipeBetweenFrames = false;
  11258. /**
  11259. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11260. **/
  11261. this.enableOfflineSupport = false;
  11262. /**
  11263. * 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)
  11264. **/
  11265. this.disableManifestCheck = false;
  11266. /**
  11267. * Gets the list of created scenes
  11268. */
  11269. this.scenes = new Array();
  11270. /**
  11271. * Gets the list of created postprocesses
  11272. */
  11273. this.postProcesses = new Array();
  11274. // Observables
  11275. /**
  11276. * Observable event triggered each time the rendering canvas is resized
  11277. */
  11278. this.onResizeObservable = new BABYLON.Observable();
  11279. /**
  11280. * Observable event triggered each time the canvas loses focus
  11281. */
  11282. this.onCanvasBlurObservable = new BABYLON.Observable();
  11283. /**
  11284. * Observable event triggered each time the canvas gains focus
  11285. */
  11286. this.onCanvasFocusObservable = new BABYLON.Observable();
  11287. /**
  11288. * Observable event triggered each time the canvas receives pointerout event
  11289. */
  11290. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11291. /**
  11292. * Observable event triggered before each texture is initialized
  11293. */
  11294. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11295. //WebVR
  11296. this._vrDisplay = undefined;
  11297. this._vrSupported = false;
  11298. this._vrExclusivePointerMode = false;
  11299. // Uniform buffers list
  11300. /**
  11301. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11302. */
  11303. this.disableUniformBuffers = false;
  11304. /** @hidden */
  11305. this._uniformBuffers = new Array();
  11306. // Observables
  11307. /**
  11308. * Observable raised when the engine begins a new frame
  11309. */
  11310. this.onBeginFrameObservable = new BABYLON.Observable();
  11311. /**
  11312. * Observable raised when the engine ends the current frame
  11313. */
  11314. this.onEndFrameObservable = new BABYLON.Observable();
  11315. /**
  11316. * Observable raised when the engine is about to compile a shader
  11317. */
  11318. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11319. /**
  11320. * Observable raised when the engine has jsut compiled a shader
  11321. */
  11322. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11323. this._windowIsBackground = false;
  11324. this._webGLVersion = 1.0;
  11325. /** @hidden */
  11326. this._badOS = false;
  11327. /** @hidden */
  11328. this._badDesktopOS = false;
  11329. /**
  11330. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11331. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11332. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11333. */
  11334. this.disableTextureBindingOptimization = false;
  11335. /**
  11336. * Observable signaled when VR display mode changes
  11337. */
  11338. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11339. /**
  11340. * Observable signaled when VR request present is complete
  11341. */
  11342. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11343. /**
  11344. * Observable signaled when VR request present starts
  11345. */
  11346. this.onVRRequestPresentStart = new BABYLON.Observable();
  11347. this._colorWrite = true;
  11348. /** @hidden */
  11349. this._drawCalls = new BABYLON.PerfCounter();
  11350. /** @hidden */
  11351. this._textureCollisions = new BABYLON.PerfCounter();
  11352. this._renderingQueueLaunched = false;
  11353. this._activeRenderLoops = new Array();
  11354. // Deterministic lockstepMaxSteps
  11355. this._deterministicLockstep = false;
  11356. this._lockstepMaxSteps = 4;
  11357. // Lost context
  11358. /**
  11359. * Observable signaled when a context lost event is raised
  11360. */
  11361. this.onContextLostObservable = new BABYLON.Observable();
  11362. /**
  11363. * Observable signaled when a context restored event is raised
  11364. */
  11365. this.onContextRestoredObservable = new BABYLON.Observable();
  11366. this._contextWasLost = false;
  11367. this._doNotHandleContextLost = false;
  11368. // FPS
  11369. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11370. this._fps = 60;
  11371. this._deltaTime = 0;
  11372. /**
  11373. * Turn this value on if you want to pause FPS computation when in background
  11374. */
  11375. this.disablePerformanceMonitorInBackground = false;
  11376. // States
  11377. /** @hidden */
  11378. this._depthCullingState = new BABYLON._DepthCullingState();
  11379. /** @hidden */
  11380. this._stencilState = new BABYLON._StencilState();
  11381. /** @hidden */
  11382. this._alphaState = new BABYLON._AlphaState();
  11383. /** @hidden */
  11384. this._alphaMode = Engine.ALPHA_DISABLE;
  11385. // Cache
  11386. this._internalTexturesCache = new Array();
  11387. /** @hidden */
  11388. this._activeChannel = 0;
  11389. this._currentTextureChannel = -1;
  11390. /** @hidden */
  11391. this._boundTexturesCache = {};
  11392. this._compiledEffects = {};
  11393. this._vertexAttribArraysEnabled = [];
  11394. this._uintIndicesCurrentlySet = false;
  11395. this._currentBoundBuffer = new Array();
  11396. this._currentBufferPointers = new Array();
  11397. this._currentInstanceLocations = new Array();
  11398. this._currentInstanceBuffers = new Array();
  11399. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11400. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11401. this._vaoRecordInProgress = false;
  11402. this._mustWipeVertexAttributes = false;
  11403. this._nextFreeTextureSlots = new Array();
  11404. this._maxSimultaneousTextures = 0;
  11405. this._activeRequests = new Array();
  11406. // Hardware supported Compressed Textures
  11407. this._texturesSupported = new Array();
  11408. /**
  11409. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11410. */
  11411. this.premultipliedAlpha = true;
  11412. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11413. this._onVRFullScreenTriggered = function () {
  11414. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11415. //get the old size before we change
  11416. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11417. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11418. //get the width and height, change the render size
  11419. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11420. _this.setHardwareScalingLevel(1);
  11421. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11422. }
  11423. else {
  11424. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11425. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11426. }
  11427. };
  11428. this._unpackFlipYCached = null;
  11429. this._boundUniforms = {};
  11430. // Register promises
  11431. BABYLON.PromisePolyfill.Apply();
  11432. var canvas = null;
  11433. Engine.Instances.push(this);
  11434. if (!canvasOrContext) {
  11435. return;
  11436. }
  11437. options = options || {};
  11438. if (canvasOrContext.getContext) {
  11439. canvas = canvasOrContext;
  11440. this._renderingCanvas = canvas;
  11441. if (antialias != null) {
  11442. options.antialias = antialias;
  11443. }
  11444. if (options.deterministicLockstep === undefined) {
  11445. options.deterministicLockstep = false;
  11446. }
  11447. if (options.lockstepMaxSteps === undefined) {
  11448. options.lockstepMaxSteps = 4;
  11449. }
  11450. if (options.preserveDrawingBuffer === undefined) {
  11451. options.preserveDrawingBuffer = false;
  11452. }
  11453. if (options.audioEngine === undefined) {
  11454. options.audioEngine = true;
  11455. }
  11456. if (options.stencil === undefined) {
  11457. options.stencil = true;
  11458. }
  11459. if (options.premultipliedAlpha === false) {
  11460. this.premultipliedAlpha = false;
  11461. }
  11462. this._deterministicLockstep = options.deterministicLockstep;
  11463. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11464. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11465. // Exceptions
  11466. if (navigator && navigator.userAgent) {
  11467. var ua = navigator.userAgent;
  11468. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11469. var exception = _a[_i];
  11470. var key = exception.key;
  11471. var targets = exception.targets;
  11472. if (ua.indexOf(key) > -1) {
  11473. if (exception.capture && exception.captureConstraint) {
  11474. var capture = exception.capture;
  11475. var constraint = exception.captureConstraint;
  11476. var regex = new RegExp(capture);
  11477. var matches = regex.exec(ua);
  11478. if (matches && matches.length > 0) {
  11479. var capturedValue = parseInt(matches[matches.length - 1]);
  11480. if (capturedValue >= constraint) {
  11481. continue;
  11482. }
  11483. }
  11484. }
  11485. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11486. var target = targets_1[_b];
  11487. switch (target) {
  11488. case "uniformBuffer":
  11489. this.disableUniformBuffers = true;
  11490. break;
  11491. case "textureBindingOptimization":
  11492. this.disableTextureBindingOptimization = true;
  11493. break;
  11494. }
  11495. }
  11496. }
  11497. }
  11498. }
  11499. // GL
  11500. if (!options.disableWebGL2Support) {
  11501. try {
  11502. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11503. if (this._gl) {
  11504. this._webGLVersion = 2.0;
  11505. }
  11506. }
  11507. catch (e) {
  11508. // Do nothing
  11509. }
  11510. }
  11511. if (!this._gl) {
  11512. if (!canvas) {
  11513. throw new Error("The provided canvas is null or undefined.");
  11514. }
  11515. try {
  11516. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11517. }
  11518. catch (e) {
  11519. throw new Error("WebGL not supported");
  11520. }
  11521. }
  11522. if (!this._gl) {
  11523. throw new Error("WebGL not supported");
  11524. }
  11525. this._onCanvasFocus = function () {
  11526. _this.onCanvasFocusObservable.notifyObservers(_this);
  11527. };
  11528. this._onCanvasBlur = function () {
  11529. _this.onCanvasBlurObservable.notifyObservers(_this);
  11530. };
  11531. canvas.addEventListener("focus", this._onCanvasFocus);
  11532. canvas.addEventListener("blur", this._onCanvasBlur);
  11533. this._onBlur = function () {
  11534. if (_this.disablePerformanceMonitorInBackground) {
  11535. _this._performanceMonitor.disable();
  11536. }
  11537. _this._windowIsBackground = true;
  11538. };
  11539. this._onFocus = function () {
  11540. if (_this.disablePerformanceMonitorInBackground) {
  11541. _this._performanceMonitor.enable();
  11542. }
  11543. _this._windowIsBackground = false;
  11544. };
  11545. this._onCanvasPointerOut = function (ev) {
  11546. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11547. };
  11548. window.addEventListener("blur", this._onBlur);
  11549. window.addEventListener("focus", this._onFocus);
  11550. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11551. // Context lost
  11552. if (!this._doNotHandleContextLost) {
  11553. this._onContextLost = function (evt) {
  11554. evt.preventDefault();
  11555. _this._contextWasLost = true;
  11556. BABYLON.Tools.Warn("WebGL context lost.");
  11557. _this.onContextLostObservable.notifyObservers(_this);
  11558. };
  11559. this._onContextRestored = function (evt) {
  11560. // Adding a timeout to avoid race condition at browser level
  11561. setTimeout(function () {
  11562. // Rebuild gl context
  11563. _this._initGLContext();
  11564. // Rebuild effects
  11565. _this._rebuildEffects();
  11566. // Rebuild textures
  11567. _this._rebuildInternalTextures();
  11568. // Rebuild buffers
  11569. _this._rebuildBuffers();
  11570. // Cache
  11571. _this.wipeCaches(true);
  11572. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11573. _this.onContextRestoredObservable.notifyObservers(_this);
  11574. _this._contextWasLost = false;
  11575. }, 0);
  11576. };
  11577. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11578. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11579. }
  11580. }
  11581. else {
  11582. this._gl = canvasOrContext;
  11583. this._renderingCanvas = this._gl.canvas;
  11584. if (this._gl.renderbufferStorageMultisample) {
  11585. this._webGLVersion = 2.0;
  11586. }
  11587. options.stencil = this._gl.getContextAttributes().stencil;
  11588. }
  11589. // Viewport
  11590. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11591. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11592. this.resize();
  11593. this._isStencilEnable = options.stencil ? true : false;
  11594. this._initGLContext();
  11595. if (canvas) {
  11596. // Fullscreen
  11597. this._onFullscreenChange = function () {
  11598. if (document.fullscreen !== undefined) {
  11599. _this.isFullscreen = document.fullscreen;
  11600. }
  11601. else if (document.mozFullScreen !== undefined) {
  11602. _this.isFullscreen = document.mozFullScreen;
  11603. }
  11604. else if (document.webkitIsFullScreen !== undefined) {
  11605. _this.isFullscreen = document.webkitIsFullScreen;
  11606. }
  11607. else if (document.msIsFullScreen !== undefined) {
  11608. _this.isFullscreen = document.msIsFullScreen;
  11609. }
  11610. // Pointer lock
  11611. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11612. canvas.requestPointerLock = canvas.requestPointerLock ||
  11613. canvas.msRequestPointerLock ||
  11614. canvas.mozRequestPointerLock ||
  11615. canvas.webkitRequestPointerLock;
  11616. if (canvas.requestPointerLock) {
  11617. canvas.requestPointerLock();
  11618. }
  11619. }
  11620. };
  11621. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11622. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11623. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11624. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11625. // Pointer lock
  11626. this._onPointerLockChange = function () {
  11627. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11628. document.webkitPointerLockElement === canvas ||
  11629. document.msPointerLockElement === canvas ||
  11630. document.pointerLockElement === canvas);
  11631. };
  11632. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11633. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11634. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11635. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11636. this._onVRDisplayPointerRestricted = function () {
  11637. if (canvas) {
  11638. canvas.requestPointerLock();
  11639. }
  11640. };
  11641. this._onVRDisplayPointerUnrestricted = function () {
  11642. document.exitPointerLock();
  11643. };
  11644. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11645. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11646. }
  11647. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11648. Engine.audioEngine = new BABYLON.AudioEngine();
  11649. }
  11650. // Prepare buffer pointers
  11651. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11652. this._currentBufferPointers[i] = new BufferPointer();
  11653. }
  11654. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11655. // Load WebVR Devices
  11656. if (options.autoEnableWebVR) {
  11657. this.initWebVR();
  11658. }
  11659. // Detect if we are running on a faulty buggy OS.
  11660. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11661. // Detect if we are running on a faulty buggy desktop OS.
  11662. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11663. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11664. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11665. }
  11666. Object.defineProperty(Engine, "LastCreatedEngine", {
  11667. /**
  11668. * Gets the latest created engine
  11669. */
  11670. get: function () {
  11671. if (Engine.Instances.length === 0) {
  11672. return null;
  11673. }
  11674. return Engine.Instances[Engine.Instances.length - 1];
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(Engine, "LastCreatedScene", {
  11680. /**
  11681. * Gets the latest created scene
  11682. */
  11683. get: function () {
  11684. var lastCreatedEngine = Engine.LastCreatedEngine;
  11685. if (!lastCreatedEngine) {
  11686. return null;
  11687. }
  11688. if (lastCreatedEngine.scenes.length === 0) {
  11689. return null;
  11690. }
  11691. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. /**
  11697. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11698. * @param flag defines which part of the materials must be marked as dirty
  11699. * @param predicate defines a predicate used to filter which materials should be affected
  11700. */
  11701. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11702. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11703. var engine = Engine.Instances[engineIndex];
  11704. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11705. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11706. }
  11707. }
  11708. };
  11709. Object.defineProperty(Engine, "NEVER", {
  11710. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11711. get: function () {
  11712. return Engine._NEVER;
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. Object.defineProperty(Engine, "ALWAYS", {
  11718. /** 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 */
  11719. get: function () {
  11720. return Engine._ALWAYS;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine, "LESS", {
  11726. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11727. get: function () {
  11728. return Engine._LESS;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine, "EQUAL", {
  11734. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11735. get: function () {
  11736. return Engine._EQUAL;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Engine, "LEQUAL", {
  11742. /** 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 */
  11743. get: function () {
  11744. return Engine._LEQUAL;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(Engine, "GREATER", {
  11750. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11751. get: function () {
  11752. return Engine._GREATER;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Engine, "GEQUAL", {
  11758. /** 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 */
  11759. get: function () {
  11760. return Engine._GEQUAL;
  11761. },
  11762. enumerable: true,
  11763. configurable: true
  11764. });
  11765. Object.defineProperty(Engine, "NOTEQUAL", {
  11766. /** 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 */
  11767. get: function () {
  11768. return Engine._NOTEQUAL;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine, "KEEP", {
  11774. /** Passed to stencilOperation to specify that stencil value must be kept */
  11775. get: function () {
  11776. return Engine._KEEP;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine, "REPLACE", {
  11782. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11783. get: function () {
  11784. return Engine._REPLACE;
  11785. },
  11786. enumerable: true,
  11787. configurable: true
  11788. });
  11789. Object.defineProperty(Engine, "INCR", {
  11790. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11791. get: function () {
  11792. return Engine._INCR;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine, "DECR", {
  11798. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11799. get: function () {
  11800. return Engine._DECR;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(Engine, "INVERT", {
  11806. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11807. get: function () {
  11808. return Engine._INVERT;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "INCR_WRAP", {
  11814. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11815. get: function () {
  11816. return Engine._INCR_WRAP;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "DECR_WRAP", {
  11822. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11823. get: function () {
  11824. return Engine._DECR_WRAP;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11830. // Alpha
  11831. /** Defines that alpha blending is disabled */
  11832. get: function () {
  11833. return Engine._ALPHA_DISABLE;
  11834. },
  11835. enumerable: true,
  11836. configurable: true
  11837. });
  11838. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11839. /** Defines that alpha blending to SRC + DEST */
  11840. get: function () {
  11841. return Engine._ALPHA_ONEONE;
  11842. },
  11843. enumerable: true,
  11844. configurable: true
  11845. });
  11846. Object.defineProperty(Engine, "ALPHA_ADD", {
  11847. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11848. get: function () {
  11849. return Engine._ALPHA_ADD;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11855. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11856. get: function () {
  11857. return Engine._ALPHA_COMBINE;
  11858. },
  11859. enumerable: true,
  11860. configurable: true
  11861. });
  11862. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11863. /** Defines that alpha blending to DEST - SRC * DEST */
  11864. get: function () {
  11865. return Engine._ALPHA_SUBTRACT;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11871. /** Defines that alpha blending to SRC * DEST */
  11872. get: function () {
  11873. return Engine._ALPHA_MULTIPLY;
  11874. },
  11875. enumerable: true,
  11876. configurable: true
  11877. });
  11878. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11879. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11880. get: function () {
  11881. return Engine._ALPHA_MAXIMIZED;
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11887. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11888. get: function () {
  11889. return Engine._ALPHA_PREMULTIPLIED;
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11895. /**
  11896. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11897. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11898. */
  11899. get: function () {
  11900. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11906. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11907. get: function () {
  11908. return Engine._ALPHA_INTERPOLATE;
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11914. /**
  11915. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11916. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11917. */
  11918. get: function () {
  11919. return Engine._ALPHA_SCREENMODE;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11925. // Delays
  11926. /** Defines that the ressource is not delayed*/
  11927. get: function () {
  11928. return Engine._DELAYLOADSTATE_NONE;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11934. /** Defines that the ressource was successfully delay loaded */
  11935. get: function () {
  11936. return Engine._DELAYLOADSTATE_LOADED;
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11942. /** Defines that the ressource is currently delay loading */
  11943. get: function () {
  11944. return Engine._DELAYLOADSTATE_LOADING;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11950. /** Defines that the ressource is delayed and has not started loading */
  11951. get: function () {
  11952. return Engine._DELAYLOADSTATE_NOTLOADED;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11958. /** ALPHA */
  11959. get: function () {
  11960. return Engine._TEXTUREFORMAT_ALPHA;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11966. /** LUMINANCE */
  11967. get: function () {
  11968. return Engine._TEXTUREFORMAT_LUMINANCE;
  11969. },
  11970. enumerable: true,
  11971. configurable: true
  11972. });
  11973. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11974. /**
  11975. * R
  11976. */
  11977. get: function () {
  11978. return Engine._TEXTUREFORMAT_R;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11984. /**
  11985. * RG
  11986. */
  11987. get: function () {
  11988. return Engine._TEXTUREFORMAT_RG;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11994. /** LUMINANCE_ALPHA */
  11995. get: function () {
  11996. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12002. /** RGB */
  12003. get: function () {
  12004. return Engine._TEXTUREFORMAT_RGB;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12010. /** RGBA */
  12011. get: function () {
  12012. return Engine._TEXTUREFORMAT_RGBA;
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12018. /** UNSIGNED_INT */
  12019. get: function () {
  12020. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12026. /** FLOAT */
  12027. get: function () {
  12028. return Engine._TEXTURETYPE_FLOAT;
  12029. },
  12030. enumerable: true,
  12031. configurable: true
  12032. });
  12033. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12034. /** HALF_FLOAT */
  12035. get: function () {
  12036. return Engine._TEXTURETYPE_HALF_FLOAT;
  12037. },
  12038. enumerable: true,
  12039. configurable: true
  12040. });
  12041. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12042. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12043. get: function () {
  12044. return Engine._SCALEMODE_FLOOR;
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12050. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12051. get: function () {
  12052. return Engine._SCALEMODE_NEAREST;
  12053. },
  12054. enumerable: true,
  12055. configurable: true
  12056. });
  12057. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12058. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12059. get: function () {
  12060. return Engine._SCALEMODE_CEILING;
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Object.defineProperty(Engine, "Version", {
  12066. /**
  12067. * Returns the current version of the framework
  12068. */
  12069. get: function () {
  12070. return "3.3.0-alpha.9";
  12071. },
  12072. enumerable: true,
  12073. configurable: true
  12074. });
  12075. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12076. /**
  12077. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12078. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12079. */
  12080. get: function () {
  12081. return this._vrExclusivePointerMode;
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12087. /**
  12088. * Gets a boolean indicating that the engine supports uniform buffers
  12089. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12090. */
  12091. get: function () {
  12092. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12093. },
  12094. enumerable: true,
  12095. configurable: true
  12096. });
  12097. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12098. /**
  12099. * Gets a boolean indicating that only power of 2 textures are supported
  12100. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12101. */
  12102. get: function () {
  12103. return this._webGLVersion < 2 || this.forcePOTTextures;
  12104. },
  12105. enumerable: true,
  12106. configurable: true
  12107. });
  12108. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12109. /**
  12110. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12111. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12112. */
  12113. get: function () {
  12114. return this._doNotHandleContextLost;
  12115. },
  12116. set: function (value) {
  12117. this._doNotHandleContextLost = value;
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12123. /**
  12124. * Gets the performance monitor attached to this engine
  12125. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12126. */
  12127. get: function () {
  12128. return this._performanceMonitor;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12134. /**
  12135. * Gets the list of texture formats supported
  12136. */
  12137. get: function () {
  12138. return this._texturesSupported;
  12139. },
  12140. enumerable: true,
  12141. configurable: true
  12142. });
  12143. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12144. /**
  12145. * Gets the list of texture formats in use
  12146. */
  12147. get: function () {
  12148. return this._textureFormatInUse;
  12149. },
  12150. enumerable: true,
  12151. configurable: true
  12152. });
  12153. Object.defineProperty(Engine.prototype, "currentViewport", {
  12154. /**
  12155. * Gets the current viewport
  12156. */
  12157. get: function () {
  12158. return this._cachedViewport;
  12159. },
  12160. enumerable: true,
  12161. configurable: true
  12162. });
  12163. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12164. /**
  12165. * Gets the default empty texture
  12166. */
  12167. get: function () {
  12168. if (!this._emptyTexture) {
  12169. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12170. }
  12171. return this._emptyTexture;
  12172. },
  12173. enumerable: true,
  12174. configurable: true
  12175. });
  12176. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12177. /**
  12178. * Gets the default empty 3D texture
  12179. */
  12180. get: function () {
  12181. if (!this._emptyTexture3D) {
  12182. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12183. }
  12184. return this._emptyTexture3D;
  12185. },
  12186. enumerable: true,
  12187. configurable: true
  12188. });
  12189. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12190. /**
  12191. * Gets the default empty cube texture
  12192. */
  12193. get: function () {
  12194. if (!this._emptyCubeTexture) {
  12195. var faceData = new Uint8Array(4);
  12196. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12197. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12198. }
  12199. return this._emptyCubeTexture;
  12200. },
  12201. enumerable: true,
  12202. configurable: true
  12203. });
  12204. Engine.prototype._rebuildInternalTextures = function () {
  12205. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12206. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12207. var internalTexture = currentState_1[_i];
  12208. internalTexture._rebuild();
  12209. }
  12210. };
  12211. Engine.prototype._rebuildEffects = function () {
  12212. for (var key in this._compiledEffects) {
  12213. var effect = this._compiledEffects[key];
  12214. effect._prepareEffect();
  12215. }
  12216. BABYLON.Effect.ResetCache();
  12217. };
  12218. Engine.prototype._rebuildBuffers = function () {
  12219. // Index / Vertex
  12220. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12221. var scene = _a[_i];
  12222. scene.resetCachedMaterial();
  12223. scene._rebuildGeometries();
  12224. scene._rebuildTextures();
  12225. }
  12226. // Uniforms
  12227. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12228. var uniformBuffer = _c[_b];
  12229. uniformBuffer._rebuild();
  12230. }
  12231. };
  12232. Engine.prototype._initGLContext = function () {
  12233. // Caps
  12234. this._caps = new EngineCapabilities();
  12235. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12236. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12237. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12238. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12239. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12240. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12241. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12242. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12243. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12244. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12245. // Infos
  12246. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12247. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12248. if (rendererInfo != null) {
  12249. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12250. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12251. }
  12252. if (!this._glVendor) {
  12253. this._glVendor = "Unknown vendor";
  12254. }
  12255. if (!this._glRenderer) {
  12256. this._glRenderer = "Unknown renderer";
  12257. }
  12258. // Constants
  12259. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12260. if (this._gl.RGBA16F !== 0x881A) {
  12261. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12262. }
  12263. if (this._gl.RGBA32F !== 0x8814) {
  12264. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12265. }
  12266. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12267. this._gl.DEPTH24_STENCIL8 = 35056;
  12268. }
  12269. // Extensions
  12270. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12271. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12272. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12273. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12274. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12275. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12276. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12277. 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');
  12278. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12279. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12280. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12281. this._caps.highPrecisionShaderSupported = true;
  12282. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12283. if (this._caps.timerQuery) {
  12284. if (this._webGLVersion === 1) {
  12285. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12286. }
  12287. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12288. }
  12289. // Checks if some of the format renders first to allow the use of webgl inspector.
  12290. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12291. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12292. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12293. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12294. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12295. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12296. if (this._webGLVersion > 1) {
  12297. this._gl.HALF_FLOAT_OES = 0x140B;
  12298. }
  12299. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12300. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12301. // Draw buffers
  12302. if (this._webGLVersion > 1) {
  12303. this._caps.drawBuffersExtension = true;
  12304. }
  12305. else {
  12306. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12307. if (drawBuffersExtension !== null) {
  12308. this._caps.drawBuffersExtension = true;
  12309. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12310. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12311. for (var i = 0; i < 16; i++) {
  12312. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12313. }
  12314. }
  12315. else {
  12316. this._caps.drawBuffersExtension = false;
  12317. }
  12318. }
  12319. // Depth Texture
  12320. if (this._webGLVersion > 1) {
  12321. this._caps.depthTextureExtension = true;
  12322. }
  12323. else {
  12324. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12325. if (depthTextureExtension != null) {
  12326. this._caps.depthTextureExtension = true;
  12327. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12328. }
  12329. }
  12330. // Vertex array object
  12331. if (this._webGLVersion > 1) {
  12332. this._caps.vertexArrayObject = true;
  12333. }
  12334. else {
  12335. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12336. if (vertexArrayObjectExtension != null) {
  12337. this._caps.vertexArrayObject = true;
  12338. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12339. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12340. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12341. }
  12342. else {
  12343. this._caps.vertexArrayObject = false;
  12344. }
  12345. }
  12346. // Instances count
  12347. if (this._webGLVersion > 1) {
  12348. this._caps.instancedArrays = true;
  12349. }
  12350. else {
  12351. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12352. if (instanceExtension != null) {
  12353. this._caps.instancedArrays = true;
  12354. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12355. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12356. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12357. }
  12358. else {
  12359. this._caps.instancedArrays = false;
  12360. }
  12361. }
  12362. // Intelligently add supported compressed formats in order to check for.
  12363. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12364. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12365. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12366. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12367. if (this._caps.astc)
  12368. this.texturesSupported.push('-astc.ktx');
  12369. if (this._caps.s3tc)
  12370. this.texturesSupported.push('-dxt.ktx');
  12371. if (this._caps.pvrtc)
  12372. this.texturesSupported.push('-pvrtc.ktx');
  12373. if (this._caps.etc2)
  12374. this.texturesSupported.push('-etc2.ktx');
  12375. if (this._caps.etc1)
  12376. this.texturesSupported.push('-etc1.ktx');
  12377. if (this._gl.getShaderPrecisionFormat) {
  12378. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12379. if (highp) {
  12380. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12381. }
  12382. }
  12383. // Depth buffer
  12384. this.setDepthBuffer(true);
  12385. this.setDepthFunctionToLessOrEqual();
  12386. this.setDepthWrite(true);
  12387. // Texture maps
  12388. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12389. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12390. this._nextFreeTextureSlots.push(slot);
  12391. }
  12392. };
  12393. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12394. /**
  12395. * Gets version of the current webGL context
  12396. */
  12397. get: function () {
  12398. return this._webGLVersion;
  12399. },
  12400. enumerable: true,
  12401. configurable: true
  12402. });
  12403. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12404. /**
  12405. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12406. */
  12407. get: function () {
  12408. return this._isStencilEnable;
  12409. },
  12410. enumerable: true,
  12411. configurable: true
  12412. });
  12413. Engine.prototype._prepareWorkingCanvas = function () {
  12414. if (this._workingCanvas) {
  12415. return;
  12416. }
  12417. this._workingCanvas = document.createElement("canvas");
  12418. var context = this._workingCanvas.getContext("2d");
  12419. if (context) {
  12420. this._workingContext = context;
  12421. }
  12422. };
  12423. /**
  12424. * Reset the texture cache to empty state
  12425. */
  12426. Engine.prototype.resetTextureCache = function () {
  12427. for (var key in this._boundTexturesCache) {
  12428. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12429. continue;
  12430. }
  12431. var boundTexture = this._boundTexturesCache[key];
  12432. if (boundTexture) {
  12433. this._removeDesignatedSlot(boundTexture);
  12434. }
  12435. this._boundTexturesCache[key] = null;
  12436. }
  12437. if (!this.disableTextureBindingOptimization) {
  12438. this._nextFreeTextureSlots = [];
  12439. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12440. this._nextFreeTextureSlots.push(slot);
  12441. }
  12442. }
  12443. this._currentTextureChannel = -1;
  12444. };
  12445. /**
  12446. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12447. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12448. * @returns true if engine is in deterministic lock step mode
  12449. */
  12450. Engine.prototype.isDeterministicLockStep = function () {
  12451. return this._deterministicLockstep;
  12452. };
  12453. /**
  12454. * Gets the max steps when engine is running in deterministic lock step
  12455. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12456. * @returns the max steps
  12457. */
  12458. Engine.prototype.getLockstepMaxSteps = function () {
  12459. return this._lockstepMaxSteps;
  12460. };
  12461. /**
  12462. * Gets an object containing information about the current webGL context
  12463. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12464. */
  12465. Engine.prototype.getGlInfo = function () {
  12466. return {
  12467. vendor: this._glVendor,
  12468. renderer: this._glRenderer,
  12469. version: this._glVersion
  12470. };
  12471. };
  12472. /**
  12473. * Gets current aspect ratio
  12474. * @param camera defines the camera to use to get the aspect ratio
  12475. * @param useScreen defines if screen size must be used (or the current render target if any)
  12476. * @returns a number defining the aspect ratio
  12477. */
  12478. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12479. if (useScreen === void 0) { useScreen = false; }
  12480. var viewport = camera.viewport;
  12481. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12482. };
  12483. /**
  12484. * Gets current screen aspect ratio
  12485. * @returns a number defining the aspect ratio
  12486. */
  12487. Engine.prototype.getScreenAspectRatio = function () {
  12488. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12489. };
  12490. /**
  12491. * Gets the current render width
  12492. * @param useScreen defines if screen size must be used (or the current render target if any)
  12493. * @returns a number defining the current render width
  12494. */
  12495. Engine.prototype.getRenderWidth = function (useScreen) {
  12496. if (useScreen === void 0) { useScreen = false; }
  12497. if (!useScreen && this._currentRenderTarget) {
  12498. return this._currentRenderTarget.width;
  12499. }
  12500. return this._gl.drawingBufferWidth;
  12501. };
  12502. /**
  12503. * Gets the current render height
  12504. * @param useScreen defines if screen size must be used (or the current render target if any)
  12505. * @returns a number defining the current render height
  12506. */
  12507. Engine.prototype.getRenderHeight = function (useScreen) {
  12508. if (useScreen === void 0) { useScreen = false; }
  12509. if (!useScreen && this._currentRenderTarget) {
  12510. return this._currentRenderTarget.height;
  12511. }
  12512. return this._gl.drawingBufferHeight;
  12513. };
  12514. /**
  12515. * Gets the HTML canvas attached with the current webGL context
  12516. * @returns a HTML canvas
  12517. */
  12518. Engine.prototype.getRenderingCanvas = function () {
  12519. return this._renderingCanvas;
  12520. };
  12521. /**
  12522. * Gets the client rect of the HTML canvas attached with the current webGL context
  12523. * @returns a client rectanglee
  12524. */
  12525. Engine.prototype.getRenderingCanvasClientRect = function () {
  12526. if (!this._renderingCanvas) {
  12527. return null;
  12528. }
  12529. return this._renderingCanvas.getBoundingClientRect();
  12530. };
  12531. /**
  12532. * Defines the hardware scaling level.
  12533. * By default the hardware scaling level is computed from the window device ratio.
  12534. * 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.
  12535. * @param level defines the level to use
  12536. */
  12537. Engine.prototype.setHardwareScalingLevel = function (level) {
  12538. this._hardwareScalingLevel = level;
  12539. this.resize();
  12540. };
  12541. /**
  12542. * Gets the current hardware scaling level.
  12543. * By default the hardware scaling level is computed from the window device ratio.
  12544. * 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.
  12545. * @returns a number indicating the current hardware scaling level
  12546. */
  12547. Engine.prototype.getHardwareScalingLevel = function () {
  12548. return this._hardwareScalingLevel;
  12549. };
  12550. /**
  12551. * Gets the list of loaded textures
  12552. * @returns an array containing all loaded textures
  12553. */
  12554. Engine.prototype.getLoadedTexturesCache = function () {
  12555. return this._internalTexturesCache;
  12556. };
  12557. /**
  12558. * Gets the object containing all engine capabilities
  12559. * @returns the EngineCapabilities object
  12560. */
  12561. Engine.prototype.getCaps = function () {
  12562. return this._caps;
  12563. };
  12564. Object.defineProperty(Engine.prototype, "drawCalls", {
  12565. /** @hidden */
  12566. get: function () {
  12567. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12568. return 0;
  12569. },
  12570. enumerable: true,
  12571. configurable: true
  12572. });
  12573. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12574. /** @hidden */
  12575. get: function () {
  12576. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12577. return null;
  12578. },
  12579. enumerable: true,
  12580. configurable: true
  12581. });
  12582. /**
  12583. * Gets the current depth function
  12584. * @returns a number defining the depth function
  12585. */
  12586. Engine.prototype.getDepthFunction = function () {
  12587. return this._depthCullingState.depthFunc;
  12588. };
  12589. /**
  12590. * Sets the current depth function
  12591. * @param depthFunc defines the function to use
  12592. */
  12593. Engine.prototype.setDepthFunction = function (depthFunc) {
  12594. this._depthCullingState.depthFunc = depthFunc;
  12595. };
  12596. /**
  12597. * Sets the current depth function to GREATER
  12598. */
  12599. Engine.prototype.setDepthFunctionToGreater = function () {
  12600. this._depthCullingState.depthFunc = this._gl.GREATER;
  12601. };
  12602. /**
  12603. * Sets the current depth function to GEQUAL
  12604. */
  12605. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12606. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12607. };
  12608. /**
  12609. * Sets the current depth function to LESS
  12610. */
  12611. Engine.prototype.setDepthFunctionToLess = function () {
  12612. this._depthCullingState.depthFunc = this._gl.LESS;
  12613. };
  12614. /**
  12615. * Sets the current depth function to LEQUAL
  12616. */
  12617. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12618. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12619. };
  12620. /**
  12621. * Gets a boolean indicating if stencil buffer is enabled
  12622. * @returns the current stencil buffer state
  12623. */
  12624. Engine.prototype.getStencilBuffer = function () {
  12625. return this._stencilState.stencilTest;
  12626. };
  12627. /**
  12628. * Enable or disable the stencil buffer
  12629. * @param enable defines if the stencil buffer must be enabled or disabled
  12630. */
  12631. Engine.prototype.setStencilBuffer = function (enable) {
  12632. this._stencilState.stencilTest = enable;
  12633. };
  12634. /**
  12635. * Gets the current stencil mask
  12636. * @returns a number defining the new stencil mask to use
  12637. */
  12638. Engine.prototype.getStencilMask = function () {
  12639. return this._stencilState.stencilMask;
  12640. };
  12641. /**
  12642. * Sets the current stencil mask
  12643. * @param mask defines the new stencil mask to use
  12644. */
  12645. Engine.prototype.setStencilMask = function (mask) {
  12646. this._stencilState.stencilMask = mask;
  12647. };
  12648. /**
  12649. * Gets the current stencil function
  12650. * @returns a number defining the stencil function to use
  12651. */
  12652. Engine.prototype.getStencilFunction = function () {
  12653. return this._stencilState.stencilFunc;
  12654. };
  12655. /**
  12656. * Gets the current stencil reference value
  12657. * @returns a number defining the stencil reference value to use
  12658. */
  12659. Engine.prototype.getStencilFunctionReference = function () {
  12660. return this._stencilState.stencilFuncRef;
  12661. };
  12662. /**
  12663. * Gets the current stencil mask
  12664. * @returns a number defining the stencil mask to use
  12665. */
  12666. Engine.prototype.getStencilFunctionMask = function () {
  12667. return this._stencilState.stencilFuncMask;
  12668. };
  12669. /**
  12670. * Sets the current stencil function
  12671. * @param stencilFunc defines the new stencil function to use
  12672. */
  12673. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12674. this._stencilState.stencilFunc = stencilFunc;
  12675. };
  12676. /**
  12677. * Sets the current stencil reference
  12678. * @param reference defines the new stencil reference to use
  12679. */
  12680. Engine.prototype.setStencilFunctionReference = function (reference) {
  12681. this._stencilState.stencilFuncRef = reference;
  12682. };
  12683. /**
  12684. * Sets the current stencil mask
  12685. * @param mask defines the new stencil mask to use
  12686. */
  12687. Engine.prototype.setStencilFunctionMask = function (mask) {
  12688. this._stencilState.stencilFuncMask = mask;
  12689. };
  12690. /**
  12691. * Gets the current stencil operation when stencil fails
  12692. * @returns a number defining stencil operation to use when stencil fails
  12693. */
  12694. Engine.prototype.getStencilOperationFail = function () {
  12695. return this._stencilState.stencilOpStencilFail;
  12696. };
  12697. /**
  12698. * Gets the current stencil operation when depth fails
  12699. * @returns a number defining stencil operation to use when depth fails
  12700. */
  12701. Engine.prototype.getStencilOperationDepthFail = function () {
  12702. return this._stencilState.stencilOpDepthFail;
  12703. };
  12704. /**
  12705. * Gets the current stencil operation when stencil passes
  12706. * @returns a number defining stencil operation to use when stencil passes
  12707. */
  12708. Engine.prototype.getStencilOperationPass = function () {
  12709. return this._stencilState.stencilOpStencilDepthPass;
  12710. };
  12711. /**
  12712. * Sets the stencil operation to use when stencil fails
  12713. * @param operation defines the stencil operation to use when stencil fails
  12714. */
  12715. Engine.prototype.setStencilOperationFail = function (operation) {
  12716. this._stencilState.stencilOpStencilFail = operation;
  12717. };
  12718. /**
  12719. * Sets the stencil operation to use when depth fails
  12720. * @param operation defines the stencil operation to use when depth fails
  12721. */
  12722. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12723. this._stencilState.stencilOpDepthFail = operation;
  12724. };
  12725. /**
  12726. * Sets the stencil operation to use when stencil passes
  12727. * @param operation defines the stencil operation to use when stencil passes
  12728. */
  12729. Engine.prototype.setStencilOperationPass = function (operation) {
  12730. this._stencilState.stencilOpStencilDepthPass = operation;
  12731. };
  12732. /**
  12733. * Sets a boolean indicating if the dithering state is enabled or disabled
  12734. * @param value defines the dithering state
  12735. */
  12736. Engine.prototype.setDitheringState = function (value) {
  12737. if (value) {
  12738. this._gl.enable(this._gl.DITHER);
  12739. }
  12740. else {
  12741. this._gl.disable(this._gl.DITHER);
  12742. }
  12743. };
  12744. /**
  12745. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12746. * @param value defines the rasterizer state
  12747. */
  12748. Engine.prototype.setRasterizerState = function (value) {
  12749. if (value) {
  12750. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12751. }
  12752. else {
  12753. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12754. }
  12755. };
  12756. /**
  12757. * stop executing a render loop function and remove it from the execution array
  12758. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12759. */
  12760. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12761. if (!renderFunction) {
  12762. this._activeRenderLoops = [];
  12763. return;
  12764. }
  12765. var index = this._activeRenderLoops.indexOf(renderFunction);
  12766. if (index >= 0) {
  12767. this._activeRenderLoops.splice(index, 1);
  12768. }
  12769. };
  12770. /** @hidden */
  12771. Engine.prototype._renderLoop = function () {
  12772. if (!this._contextWasLost) {
  12773. var shouldRender = true;
  12774. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12775. shouldRender = false;
  12776. }
  12777. if (shouldRender) {
  12778. // Start new frame
  12779. this.beginFrame();
  12780. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12781. var renderFunction = this._activeRenderLoops[index];
  12782. renderFunction();
  12783. }
  12784. // Present
  12785. this.endFrame();
  12786. }
  12787. }
  12788. if (this._activeRenderLoops.length > 0) {
  12789. // Register new frame
  12790. var requester = null;
  12791. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12792. requester = this._vrDisplay;
  12793. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12794. }
  12795. else {
  12796. this._renderingQueueLaunched = false;
  12797. }
  12798. };
  12799. /**
  12800. * Register and execute a render loop. The engine can have more than one render function
  12801. * @param renderFunction defines the function to continuously execute
  12802. */
  12803. Engine.prototype.runRenderLoop = function (renderFunction) {
  12804. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12805. return;
  12806. }
  12807. this._activeRenderLoops.push(renderFunction);
  12808. if (!this._renderingQueueLaunched) {
  12809. this._renderingQueueLaunched = true;
  12810. this._bindedRenderFunction = this._renderLoop.bind(this);
  12811. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12812. }
  12813. };
  12814. /**
  12815. * Toggle full screen mode
  12816. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12817. * @param options defines an option object to be sent to the requestFullscreen function
  12818. */
  12819. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12820. if (this.isFullscreen) {
  12821. BABYLON.Tools.ExitFullscreen();
  12822. }
  12823. else {
  12824. this._pointerLockRequested = requestPointerLock;
  12825. if (this._renderingCanvas) {
  12826. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12827. }
  12828. }
  12829. };
  12830. /**
  12831. * Clear the current render buffer or the current render target (if any is set up)
  12832. * @param color defines the color to use
  12833. * @param backBuffer defines if the back buffer must be cleared
  12834. * @param depth defines if the depth buffer must be cleared
  12835. * @param stencil defines if the stencil buffer must be cleared
  12836. */
  12837. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12838. if (stencil === void 0) { stencil = false; }
  12839. this.applyStates();
  12840. var mode = 0;
  12841. if (backBuffer && color) {
  12842. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12843. mode |= this._gl.COLOR_BUFFER_BIT;
  12844. }
  12845. if (depth) {
  12846. this._gl.clearDepth(1.0);
  12847. mode |= this._gl.DEPTH_BUFFER_BIT;
  12848. }
  12849. if (stencil) {
  12850. this._gl.clearStencil(0);
  12851. mode |= this._gl.STENCIL_BUFFER_BIT;
  12852. }
  12853. this._gl.clear(mode);
  12854. };
  12855. /**
  12856. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12857. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12858. * @param y defines the y-coordinate of the corner of the clear rectangle
  12859. * @param width defines the width of the clear rectangle
  12860. * @param height defines the height of the clear rectangle
  12861. * @param clearColor defines the clear color
  12862. */
  12863. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12864. var gl = this._gl;
  12865. // Save state
  12866. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12867. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12868. // Change state
  12869. gl.enable(gl.SCISSOR_TEST);
  12870. gl.scissor(x, y, width, height);
  12871. // Clear
  12872. this.clear(clearColor, true, true, true);
  12873. // Restore state
  12874. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12875. if (curScissor === true) {
  12876. gl.enable(gl.SCISSOR_TEST);
  12877. }
  12878. else {
  12879. gl.disable(gl.SCISSOR_TEST);
  12880. }
  12881. };
  12882. /** @hidden */
  12883. Engine.prototype._viewport = function (x, y, width, height) {
  12884. if (x !== this._viewportCached.x ||
  12885. y !== this._viewportCached.y ||
  12886. width !== this._viewportCached.z ||
  12887. height !== this._viewportCached.w) {
  12888. this._viewportCached.x = x;
  12889. this._viewportCached.y = y;
  12890. this._viewportCached.z = width;
  12891. this._viewportCached.w = height;
  12892. this._gl.viewport(x, y, width, height);
  12893. }
  12894. };
  12895. /**
  12896. * Set the WebGL's viewport
  12897. * @param viewport defines the viewport element to be used
  12898. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12899. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12900. */
  12901. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12902. var width = requiredWidth || this.getRenderWidth();
  12903. var height = requiredHeight || this.getRenderHeight();
  12904. var x = viewport.x || 0;
  12905. var y = viewport.y || 0;
  12906. this._cachedViewport = viewport;
  12907. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12908. };
  12909. /**
  12910. * Directly set the WebGL Viewport
  12911. * @param x defines the x coordinate of the viewport (in screen space)
  12912. * @param y defines the y coordinate of the viewport (in screen space)
  12913. * @param width defines the width of the viewport (in screen space)
  12914. * @param height defines the height of the viewport (in screen space)
  12915. * @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
  12916. */
  12917. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12918. var currentViewport = this._cachedViewport;
  12919. this._cachedViewport = null;
  12920. this._viewport(x, y, width, height);
  12921. return currentViewport;
  12922. };
  12923. /**
  12924. * Begin a new frame
  12925. */
  12926. Engine.prototype.beginFrame = function () {
  12927. this.onBeginFrameObservable.notifyObservers(this);
  12928. this._measureFps();
  12929. };
  12930. /**
  12931. * Enf the current frame
  12932. */
  12933. Engine.prototype.endFrame = function () {
  12934. // Force a flush in case we are using a bad OS.
  12935. if (this._badOS) {
  12936. this.flushFramebuffer();
  12937. }
  12938. // Submit frame to the vr device, if enabled
  12939. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12940. // TODO: We should only submit the frame if we read frameData successfully.
  12941. this._vrDisplay.submitFrame();
  12942. }
  12943. this.onEndFrameObservable.notifyObservers(this);
  12944. };
  12945. /**
  12946. * Resize the view according to the canvas' size
  12947. */
  12948. Engine.prototype.resize = function () {
  12949. // We're not resizing the size of the canvas while in VR mode & presenting
  12950. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12951. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12952. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12953. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12954. }
  12955. };
  12956. /**
  12957. * Force a specific size of the canvas
  12958. * @param width defines the new canvas' width
  12959. * @param height defines the new canvas' height
  12960. */
  12961. Engine.prototype.setSize = function (width, height) {
  12962. if (!this._renderingCanvas) {
  12963. return;
  12964. }
  12965. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12966. return;
  12967. }
  12968. this._renderingCanvas.width = width;
  12969. this._renderingCanvas.height = height;
  12970. for (var index = 0; index < this.scenes.length; index++) {
  12971. var scene = this.scenes[index];
  12972. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12973. var cam = scene.cameras[camIndex];
  12974. cam._currentRenderId = 0;
  12975. }
  12976. }
  12977. if (this.onResizeObservable.hasObservers) {
  12978. this.onResizeObservable.notifyObservers(this);
  12979. }
  12980. };
  12981. // WebVR functions
  12982. /**
  12983. * Gets a boolean indicating if a webVR device was detected
  12984. * @returns true if a webVR device was detected
  12985. */
  12986. Engine.prototype.isVRDevicePresent = function () {
  12987. return !!this._vrDisplay;
  12988. };
  12989. /**
  12990. * Gets the current webVR device
  12991. * @returns the current webVR device (or null)
  12992. */
  12993. Engine.prototype.getVRDevice = function () {
  12994. return this._vrDisplay;
  12995. };
  12996. /**
  12997. * Initializes a webVR display and starts listening to display change events
  12998. * The onVRDisplayChangedObservable will be notified upon these changes
  12999. * @returns The onVRDisplayChangedObservable
  13000. */
  13001. Engine.prototype.initWebVR = function () {
  13002. this.initWebVRAsync();
  13003. return this.onVRDisplayChangedObservable;
  13004. };
  13005. /**
  13006. * Initializes a webVR display and starts listening to display change events
  13007. * The onVRDisplayChangedObservable will be notified upon these changes
  13008. * @returns A promise containing a VRDisplay and if vr is supported
  13009. */
  13010. Engine.prototype.initWebVRAsync = function () {
  13011. var _this = this;
  13012. var notifyObservers = function () {
  13013. var eventArgs = {
  13014. vrDisplay: _this._vrDisplay,
  13015. vrSupported: _this._vrSupported
  13016. };
  13017. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13018. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13019. };
  13020. if (!this._onVrDisplayConnect) {
  13021. this._onVrDisplayConnect = function (event) {
  13022. _this._vrDisplay = event.display;
  13023. notifyObservers();
  13024. };
  13025. this._onVrDisplayDisconnect = function () {
  13026. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13027. _this._vrDisplay = undefined;
  13028. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13029. notifyObservers();
  13030. };
  13031. this._onVrDisplayPresentChange = function () {
  13032. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13033. };
  13034. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13035. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13036. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13037. }
  13038. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13039. this._webVRInitPromise.then(notifyObservers);
  13040. return this._webVRInitPromise;
  13041. };
  13042. /**
  13043. * Call this function to switch to webVR mode
  13044. * Will do nothing if webVR is not supported or if there is no webVR device
  13045. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13046. */
  13047. Engine.prototype.enableVR = function () {
  13048. var _this = this;
  13049. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13050. var onResolved = function () {
  13051. _this.onVRRequestPresentComplete.notifyObservers(true);
  13052. _this._onVRFullScreenTriggered();
  13053. };
  13054. var onRejected = function () {
  13055. _this.onVRRequestPresentComplete.notifyObservers(false);
  13056. };
  13057. this.onVRRequestPresentStart.notifyObservers(this);
  13058. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13059. }
  13060. };
  13061. /**
  13062. * Call this function to leave webVR mode
  13063. * Will do nothing if webVR is not supported or if there is no webVR device
  13064. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13065. */
  13066. Engine.prototype.disableVR = function () {
  13067. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13068. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13069. }
  13070. };
  13071. Engine.prototype._getVRDisplaysAsync = function () {
  13072. var _this = this;
  13073. return new Promise(function (res, rej) {
  13074. if (navigator.getVRDisplays) {
  13075. navigator.getVRDisplays().then(function (devices) {
  13076. _this._vrSupported = true;
  13077. // note that devices may actually be an empty array. This is fine;
  13078. // we expect this._vrDisplay to be undefined in this case.
  13079. _this._vrDisplay = devices[0];
  13080. res({
  13081. vrDisplay: _this._vrDisplay,
  13082. vrSupported: _this._vrSupported
  13083. });
  13084. });
  13085. }
  13086. else {
  13087. _this._vrDisplay = undefined;
  13088. _this._vrSupported = false;
  13089. res({
  13090. vrDisplay: _this._vrDisplay,
  13091. vrSupported: _this._vrSupported
  13092. });
  13093. }
  13094. });
  13095. };
  13096. /**
  13097. * Binds the frame buffer to the specified texture.
  13098. * @param texture The texture to render to or null for the default canvas
  13099. * @param faceIndex The face of the texture to render to in case of cube texture
  13100. * @param requiredWidth The width of the target to render to
  13101. * @param requiredHeight The height of the target to render to
  13102. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13103. * @param depthStencilTexture The depth stencil texture to use to render
  13104. * @param lodLevel defines le lod level to bind to the frame buffer
  13105. */
  13106. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13107. if (lodLevel === void 0) { lodLevel = 0; }
  13108. if (this._currentRenderTarget) {
  13109. this.unBindFramebuffer(this._currentRenderTarget);
  13110. }
  13111. this._currentRenderTarget = texture;
  13112. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13113. var gl = this._gl;
  13114. if (texture.isCube) {
  13115. if (faceIndex === undefined) {
  13116. faceIndex = 0;
  13117. }
  13118. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13119. if (depthStencilTexture) {
  13120. if (depthStencilTexture._generateStencilBuffer) {
  13121. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13122. }
  13123. else {
  13124. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13125. }
  13126. }
  13127. }
  13128. if (this._cachedViewport && !forceFullscreenViewport) {
  13129. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13130. }
  13131. else {
  13132. if (!requiredWidth) {
  13133. requiredWidth = texture.width;
  13134. if (lodLevel) {
  13135. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13136. }
  13137. }
  13138. if (!requiredHeight) {
  13139. requiredHeight = texture.height;
  13140. if (lodLevel) {
  13141. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13142. }
  13143. }
  13144. this._viewport(0, 0, requiredWidth, requiredHeight);
  13145. }
  13146. this.wipeCaches();
  13147. };
  13148. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13149. if (this._currentFramebuffer !== framebuffer) {
  13150. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13151. this._currentFramebuffer = framebuffer;
  13152. }
  13153. };
  13154. /**
  13155. * Unbind the current render target texture from the webGL context
  13156. * @param texture defines the render target texture to unbind
  13157. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13158. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13159. */
  13160. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13161. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13162. this._currentRenderTarget = null;
  13163. // If MSAA, we need to bitblt back to main texture
  13164. var gl = this._gl;
  13165. if (texture._MSAAFramebuffer) {
  13166. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13167. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13168. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13169. }
  13170. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13171. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13172. gl.generateMipmap(gl.TEXTURE_2D);
  13173. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13174. }
  13175. if (onBeforeUnbind) {
  13176. if (texture._MSAAFramebuffer) {
  13177. // Bind the correct framebuffer
  13178. this.bindUnboundFramebuffer(texture._framebuffer);
  13179. }
  13180. onBeforeUnbind();
  13181. }
  13182. this.bindUnboundFramebuffer(null);
  13183. };
  13184. /**
  13185. * Unbind a list of render target textures from the webGL context
  13186. * This is used only when drawBuffer extension or webGL2 are active
  13187. * @param textures defines the render target textures to unbind
  13188. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13189. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13190. */
  13191. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13192. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13193. this._currentRenderTarget = null;
  13194. // If MSAA, we need to bitblt back to main texture
  13195. var gl = this._gl;
  13196. if (textures[0]._MSAAFramebuffer) {
  13197. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13198. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13199. var attachments = textures[0]._attachments;
  13200. if (!attachments) {
  13201. attachments = new Array(textures.length);
  13202. textures[0]._attachments = attachments;
  13203. }
  13204. for (var i = 0; i < textures.length; i++) {
  13205. var texture = textures[i];
  13206. for (var j = 0; j < attachments.length; j++) {
  13207. attachments[j] = gl.NONE;
  13208. }
  13209. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13210. gl.readBuffer(attachments[i]);
  13211. gl.drawBuffers(attachments);
  13212. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13213. }
  13214. for (var i = 0; i < attachments.length; i++) {
  13215. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13216. }
  13217. gl.drawBuffers(attachments);
  13218. }
  13219. for (var i = 0; i < textures.length; i++) {
  13220. var texture = textures[i];
  13221. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13222. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13223. gl.generateMipmap(gl.TEXTURE_2D);
  13224. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13225. }
  13226. }
  13227. if (onBeforeUnbind) {
  13228. if (textures[0]._MSAAFramebuffer) {
  13229. // Bind the correct framebuffer
  13230. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13231. }
  13232. onBeforeUnbind();
  13233. }
  13234. this.bindUnboundFramebuffer(null);
  13235. };
  13236. /**
  13237. * Force the mipmap generation for the given render target texture
  13238. * @param texture defines the render target texture to use
  13239. */
  13240. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13241. if (texture.generateMipMaps) {
  13242. var gl = this._gl;
  13243. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13244. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13245. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13246. }
  13247. };
  13248. /**
  13249. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13250. */
  13251. Engine.prototype.flushFramebuffer = function () {
  13252. this._gl.flush();
  13253. };
  13254. /**
  13255. * Unbind the current render target and bind the default framebuffer
  13256. */
  13257. Engine.prototype.restoreDefaultFramebuffer = function () {
  13258. if (this._currentRenderTarget) {
  13259. this.unBindFramebuffer(this._currentRenderTarget);
  13260. }
  13261. else {
  13262. this.bindUnboundFramebuffer(null);
  13263. }
  13264. if (this._cachedViewport) {
  13265. this.setViewport(this._cachedViewport);
  13266. }
  13267. this.wipeCaches();
  13268. };
  13269. // UBOs
  13270. /**
  13271. * Create an uniform buffer
  13272. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13273. * @param elements defines the content of the uniform buffer
  13274. * @returns the webGL uniform buffer
  13275. */
  13276. Engine.prototype.createUniformBuffer = function (elements) {
  13277. var ubo = this._gl.createBuffer();
  13278. if (!ubo) {
  13279. throw new Error("Unable to create uniform buffer");
  13280. }
  13281. this.bindUniformBuffer(ubo);
  13282. if (elements instanceof Float32Array) {
  13283. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13284. }
  13285. else {
  13286. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13287. }
  13288. this.bindUniformBuffer(null);
  13289. ubo.references = 1;
  13290. return ubo;
  13291. };
  13292. /**
  13293. * Create a dynamic uniform buffer
  13294. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13295. * @param elements defines the content of the uniform buffer
  13296. * @returns the webGL uniform buffer
  13297. */
  13298. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13299. var ubo = this._gl.createBuffer();
  13300. if (!ubo) {
  13301. throw new Error("Unable to create dynamic uniform buffer");
  13302. }
  13303. this.bindUniformBuffer(ubo);
  13304. if (elements instanceof Float32Array) {
  13305. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13306. }
  13307. else {
  13308. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13309. }
  13310. this.bindUniformBuffer(null);
  13311. ubo.references = 1;
  13312. return ubo;
  13313. };
  13314. /**
  13315. * Update an existing uniform buffer
  13316. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13317. * @param uniformBuffer defines the target uniform buffer
  13318. * @param elements defines the content to update
  13319. * @param offset defines the offset in the uniform buffer where update should start
  13320. * @param count defines the size of the data to update
  13321. */
  13322. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13323. this.bindUniformBuffer(uniformBuffer);
  13324. if (offset === undefined) {
  13325. offset = 0;
  13326. }
  13327. if (count === undefined) {
  13328. if (elements instanceof Float32Array) {
  13329. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13330. }
  13331. else {
  13332. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13333. }
  13334. }
  13335. else {
  13336. if (elements instanceof Float32Array) {
  13337. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13338. }
  13339. else {
  13340. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13341. }
  13342. }
  13343. this.bindUniformBuffer(null);
  13344. };
  13345. // VBOs
  13346. Engine.prototype._resetVertexBufferBinding = function () {
  13347. this.bindArrayBuffer(null);
  13348. this._cachedVertexBuffers = null;
  13349. };
  13350. /**
  13351. * Creates a vertex buffer
  13352. * @param data the data for the vertex buffer
  13353. * @returns the new WebGL static buffer
  13354. */
  13355. Engine.prototype.createVertexBuffer = function (data) {
  13356. var vbo = this._gl.createBuffer();
  13357. if (!vbo) {
  13358. throw new Error("Unable to create vertex buffer");
  13359. }
  13360. this.bindArrayBuffer(vbo);
  13361. if (data instanceof Array) {
  13362. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13363. }
  13364. else {
  13365. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13366. }
  13367. this._resetVertexBufferBinding();
  13368. vbo.references = 1;
  13369. return vbo;
  13370. };
  13371. /**
  13372. * Creates a dynamic vertex buffer
  13373. * @param data the data for the dynamic vertex buffer
  13374. * @returns the new WebGL dynamic buffer
  13375. */
  13376. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13377. var vbo = this._gl.createBuffer();
  13378. if (!vbo) {
  13379. throw new Error("Unable to create dynamic vertex buffer");
  13380. }
  13381. this.bindArrayBuffer(vbo);
  13382. if (data instanceof Array) {
  13383. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13384. }
  13385. else {
  13386. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13387. }
  13388. this._resetVertexBufferBinding();
  13389. vbo.references = 1;
  13390. return vbo;
  13391. };
  13392. /**
  13393. * Update a dynamic index buffer
  13394. * @param indexBuffer defines the target index buffer
  13395. * @param indices defines the data to update
  13396. * @param offset defines the offset in the target index buffer where update should start
  13397. */
  13398. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13399. if (offset === void 0) { offset = 0; }
  13400. // Force cache update
  13401. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13402. this.bindIndexBuffer(indexBuffer);
  13403. var arrayBuffer;
  13404. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13405. arrayBuffer = indices;
  13406. }
  13407. else {
  13408. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13409. }
  13410. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13411. this._resetIndexBufferBinding();
  13412. };
  13413. /**
  13414. * Updates a dynamic vertex buffer.
  13415. * @param vertexBuffer the vertex buffer to update
  13416. * @param data the data used to update the vertex buffer
  13417. * @param byteOffset the byte offset of the data
  13418. * @param byteLength the byte length of the data
  13419. */
  13420. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13421. this.bindArrayBuffer(vertexBuffer);
  13422. if (byteOffset === undefined) {
  13423. byteOffset = 0;
  13424. }
  13425. if (byteLength === undefined) {
  13426. if (data instanceof Array) {
  13427. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13428. }
  13429. else {
  13430. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13431. }
  13432. }
  13433. else {
  13434. if (data instanceof Array) {
  13435. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13436. }
  13437. else {
  13438. if (data instanceof ArrayBuffer) {
  13439. data = new Uint8Array(data, byteOffset, byteLength);
  13440. }
  13441. else {
  13442. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13443. }
  13444. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13445. }
  13446. }
  13447. this._resetVertexBufferBinding();
  13448. };
  13449. Engine.prototype._resetIndexBufferBinding = function () {
  13450. this.bindIndexBuffer(null);
  13451. this._cachedIndexBuffer = null;
  13452. };
  13453. /**
  13454. * Creates a new index buffer
  13455. * @param indices defines the content of the index buffer
  13456. * @param updatable defines if the index buffer must be updatable
  13457. * @returns a new webGL buffer
  13458. */
  13459. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13460. var vbo = this._gl.createBuffer();
  13461. if (!vbo) {
  13462. throw new Error("Unable to create index buffer");
  13463. }
  13464. this.bindIndexBuffer(vbo);
  13465. // Check for 32 bits indices
  13466. var arrayBuffer;
  13467. var need32Bits = false;
  13468. if (indices instanceof Uint16Array) {
  13469. arrayBuffer = indices;
  13470. }
  13471. else {
  13472. //check 32 bit support
  13473. if (this._caps.uintIndices) {
  13474. if (indices instanceof Uint32Array) {
  13475. arrayBuffer = indices;
  13476. need32Bits = true;
  13477. }
  13478. else {
  13479. //number[] or Int32Array, check if 32 bit is necessary
  13480. for (var index = 0; index < indices.length; index++) {
  13481. if (indices[index] > 65535) {
  13482. need32Bits = true;
  13483. break;
  13484. }
  13485. }
  13486. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13487. }
  13488. }
  13489. else {
  13490. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13491. arrayBuffer = new Uint16Array(indices);
  13492. }
  13493. }
  13494. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13495. this._resetIndexBufferBinding();
  13496. vbo.references = 1;
  13497. vbo.is32Bits = need32Bits;
  13498. return vbo;
  13499. };
  13500. /**
  13501. * Bind a webGL buffer to the webGL context
  13502. * @param buffer defines the buffer to bind
  13503. */
  13504. Engine.prototype.bindArrayBuffer = function (buffer) {
  13505. if (!this._vaoRecordInProgress) {
  13506. this._unbindVertexArrayObject();
  13507. }
  13508. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13509. };
  13510. /**
  13511. * Bind an uniform buffer to the current webGL context
  13512. * @param buffer defines the buffer to bind
  13513. */
  13514. Engine.prototype.bindUniformBuffer = function (buffer) {
  13515. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13516. };
  13517. /**
  13518. * Bind a buffer to the current webGL context at a given location
  13519. * @param buffer defines the buffer to bind
  13520. * @param location defines the index where to bind the buffer
  13521. */
  13522. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13523. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13524. };
  13525. /**
  13526. * Bind a specific block at a given index in a specific shader program
  13527. * @param shaderProgram defines the shader program
  13528. * @param blockName defines the block name
  13529. * @param index defines the index where to bind the block
  13530. */
  13531. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13532. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13533. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13534. };
  13535. ;
  13536. Engine.prototype.bindIndexBuffer = function (buffer) {
  13537. if (!this._vaoRecordInProgress) {
  13538. this._unbindVertexArrayObject();
  13539. }
  13540. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13541. };
  13542. Engine.prototype.bindBuffer = function (buffer, target) {
  13543. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13544. this._gl.bindBuffer(target, buffer);
  13545. this._currentBoundBuffer[target] = buffer;
  13546. }
  13547. };
  13548. /**
  13549. * update the bound buffer with the given data
  13550. * @param data defines the data to update
  13551. */
  13552. Engine.prototype.updateArrayBuffer = function (data) {
  13553. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13554. };
  13555. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13556. var pointer = this._currentBufferPointers[indx];
  13557. var changed = false;
  13558. if (!pointer.active) {
  13559. changed = true;
  13560. pointer.active = true;
  13561. pointer.index = indx;
  13562. pointer.size = size;
  13563. pointer.type = type;
  13564. pointer.normalized = normalized;
  13565. pointer.stride = stride;
  13566. pointer.offset = offset;
  13567. pointer.buffer = buffer;
  13568. }
  13569. else {
  13570. if (pointer.buffer !== buffer) {
  13571. pointer.buffer = buffer;
  13572. changed = true;
  13573. }
  13574. if (pointer.size !== size) {
  13575. pointer.size = size;
  13576. changed = true;
  13577. }
  13578. if (pointer.type !== type) {
  13579. pointer.type = type;
  13580. changed = true;
  13581. }
  13582. if (pointer.normalized !== normalized) {
  13583. pointer.normalized = normalized;
  13584. changed = true;
  13585. }
  13586. if (pointer.stride !== stride) {
  13587. pointer.stride = stride;
  13588. changed = true;
  13589. }
  13590. if (pointer.offset !== offset) {
  13591. pointer.offset = offset;
  13592. changed = true;
  13593. }
  13594. }
  13595. if (changed || this._vaoRecordInProgress) {
  13596. this.bindArrayBuffer(buffer);
  13597. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13598. }
  13599. };
  13600. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13601. if (indexBuffer == null) {
  13602. return;
  13603. }
  13604. if (this._cachedIndexBuffer !== indexBuffer) {
  13605. this._cachedIndexBuffer = indexBuffer;
  13606. this.bindIndexBuffer(indexBuffer);
  13607. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13608. }
  13609. };
  13610. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13611. var attributes = effect.getAttributesNames();
  13612. if (!this._vaoRecordInProgress) {
  13613. this._unbindVertexArrayObject();
  13614. }
  13615. this.unbindAllAttributes();
  13616. for (var index = 0; index < attributes.length; index++) {
  13617. var order = effect.getAttributeLocation(index);
  13618. if (order >= 0) {
  13619. var vertexBuffer = vertexBuffers[attributes[index]];
  13620. if (!vertexBuffer) {
  13621. continue;
  13622. }
  13623. this._gl.enableVertexAttribArray(order);
  13624. if (!this._vaoRecordInProgress) {
  13625. this._vertexAttribArraysEnabled[order] = true;
  13626. }
  13627. var buffer = vertexBuffer.getBuffer();
  13628. if (buffer) {
  13629. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13630. if (vertexBuffer.getIsInstanced()) {
  13631. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13632. if (!this._vaoRecordInProgress) {
  13633. this._currentInstanceLocations.push(order);
  13634. this._currentInstanceBuffers.push(buffer);
  13635. }
  13636. }
  13637. }
  13638. }
  13639. }
  13640. };
  13641. /**
  13642. * Records a vertex array object
  13643. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13644. * @param vertexBuffers defines the list of vertex buffers to store
  13645. * @param indexBuffer defines the index buffer to store
  13646. * @param effect defines the effect to store
  13647. * @returns the new vertex array object
  13648. */
  13649. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13650. var vao = this._gl.createVertexArray();
  13651. this._vaoRecordInProgress = true;
  13652. this._gl.bindVertexArray(vao);
  13653. this._mustWipeVertexAttributes = true;
  13654. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13655. this.bindIndexBuffer(indexBuffer);
  13656. this._vaoRecordInProgress = false;
  13657. this._gl.bindVertexArray(null);
  13658. return vao;
  13659. };
  13660. /**
  13661. * Bind a specific vertex array object
  13662. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13663. * @param vertexArrayObject defines the vertex array object to bind
  13664. * @param indexBuffer defines the index buffer to bind
  13665. */
  13666. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13667. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13668. this._cachedVertexArrayObject = vertexArrayObject;
  13669. this._gl.bindVertexArray(vertexArrayObject);
  13670. this._cachedVertexBuffers = null;
  13671. this._cachedIndexBuffer = null;
  13672. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13673. this._mustWipeVertexAttributes = true;
  13674. }
  13675. };
  13676. /**
  13677. * Bind webGl buffers directly to the webGL context
  13678. * @param vertexBuffer defines the vertex buffer to bind
  13679. * @param indexBuffer defines the index buffer to bind
  13680. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13681. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13682. * @param effect defines the effect associated with the vertex buffer
  13683. */
  13684. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13685. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13686. this._cachedVertexBuffers = vertexBuffer;
  13687. this._cachedEffectForVertexBuffers = effect;
  13688. var attributesCount = effect.getAttributesCount();
  13689. this._unbindVertexArrayObject();
  13690. this.unbindAllAttributes();
  13691. var offset = 0;
  13692. for (var index = 0; index < attributesCount; index++) {
  13693. if (index < vertexDeclaration.length) {
  13694. var order = effect.getAttributeLocation(index);
  13695. if (order >= 0) {
  13696. this._gl.enableVertexAttribArray(order);
  13697. this._vertexAttribArraysEnabled[order] = true;
  13698. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13699. }
  13700. offset += vertexDeclaration[index] * 4;
  13701. }
  13702. }
  13703. }
  13704. this._bindIndexBufferWithCache(indexBuffer);
  13705. };
  13706. Engine.prototype._unbindVertexArrayObject = function () {
  13707. if (!this._cachedVertexArrayObject) {
  13708. return;
  13709. }
  13710. this._cachedVertexArrayObject = null;
  13711. this._gl.bindVertexArray(null);
  13712. };
  13713. /**
  13714. * Bind a list of vertex buffers to the webGL context
  13715. * @param vertexBuffers defines the list of vertex buffers to bind
  13716. * @param indexBuffer defines the index buffer to bind
  13717. * @param effect defines the effect associated with the vertex buffers
  13718. */
  13719. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13720. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13721. this._cachedVertexBuffers = vertexBuffers;
  13722. this._cachedEffectForVertexBuffers = effect;
  13723. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13724. }
  13725. this._bindIndexBufferWithCache(indexBuffer);
  13726. };
  13727. /**
  13728. * Unbind all instance attributes
  13729. */
  13730. Engine.prototype.unbindInstanceAttributes = function () {
  13731. var boundBuffer;
  13732. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13733. var instancesBuffer = this._currentInstanceBuffers[i];
  13734. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13735. boundBuffer = instancesBuffer;
  13736. this.bindArrayBuffer(instancesBuffer);
  13737. }
  13738. var offsetLocation = this._currentInstanceLocations[i];
  13739. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13740. }
  13741. this._currentInstanceBuffers.length = 0;
  13742. this._currentInstanceLocations.length = 0;
  13743. };
  13744. /**
  13745. * Release and free the memory of a vertex array object
  13746. * @param vao defines the vertex array object to delete
  13747. */
  13748. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13749. this._gl.deleteVertexArray(vao);
  13750. };
  13751. /** @hidden */
  13752. Engine.prototype._releaseBuffer = function (buffer) {
  13753. buffer.references--;
  13754. if (buffer.references === 0) {
  13755. this._gl.deleteBuffer(buffer);
  13756. return true;
  13757. }
  13758. return false;
  13759. };
  13760. /**
  13761. * Creates a webGL buffer to use with instanciation
  13762. * @param capacity defines the size of the buffer
  13763. * @returns the webGL buffer
  13764. */
  13765. Engine.prototype.createInstancesBuffer = function (capacity) {
  13766. var buffer = this._gl.createBuffer();
  13767. if (!buffer) {
  13768. throw new Error("Unable to create instance buffer");
  13769. }
  13770. buffer.capacity = capacity;
  13771. this.bindArrayBuffer(buffer);
  13772. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13773. return buffer;
  13774. };
  13775. /**
  13776. * Delete a webGL buffer used with instanciation
  13777. * @param buffer defines the webGL buffer to delete
  13778. */
  13779. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13780. this._gl.deleteBuffer(buffer);
  13781. };
  13782. /**
  13783. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13784. * @param instancesBuffer defines the webGL buffer to update and bind
  13785. * @param data defines the data to store in the buffer
  13786. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13787. */
  13788. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13789. this.bindArrayBuffer(instancesBuffer);
  13790. if (data) {
  13791. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13792. }
  13793. if (offsetLocations[0].index !== undefined) {
  13794. var stride = 0;
  13795. for (var i = 0; i < offsetLocations.length; i++) {
  13796. var ai = offsetLocations[i];
  13797. stride += ai.attributeSize * 4;
  13798. }
  13799. for (var i = 0; i < offsetLocations.length; i++) {
  13800. var ai = offsetLocations[i];
  13801. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13802. this._gl.enableVertexAttribArray(ai.index);
  13803. this._vertexAttribArraysEnabled[ai.index] = true;
  13804. }
  13805. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13806. this._gl.vertexAttribDivisor(ai.index, 1);
  13807. this._currentInstanceLocations.push(ai.index);
  13808. this._currentInstanceBuffers.push(instancesBuffer);
  13809. }
  13810. }
  13811. else {
  13812. for (var index = 0; index < 4; index++) {
  13813. var offsetLocation = offsetLocations[index];
  13814. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13815. this._gl.enableVertexAttribArray(offsetLocation);
  13816. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13817. }
  13818. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13819. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13820. this._currentInstanceLocations.push(offsetLocation);
  13821. this._currentInstanceBuffers.push(instancesBuffer);
  13822. }
  13823. }
  13824. };
  13825. /**
  13826. * Apply all cached states (depth, culling, stencil and alpha)
  13827. */
  13828. Engine.prototype.applyStates = function () {
  13829. this._depthCullingState.apply(this._gl);
  13830. this._stencilState.apply(this._gl);
  13831. this._alphaState.apply(this._gl);
  13832. };
  13833. /**
  13834. * Send a draw order
  13835. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13836. * @param indexStart defines the starting index
  13837. * @param indexCount defines the number of index to draw
  13838. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13839. */
  13840. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13841. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13842. };
  13843. /**
  13844. * Draw a list of points
  13845. * @param verticesStart defines the index of first vertex to draw
  13846. * @param verticesCount defines the count of vertices to draw
  13847. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13848. */
  13849. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13850. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13851. };
  13852. /**
  13853. * Draw a list of unindexed primitives
  13854. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13855. * @param verticesStart defines the index of first vertex to draw
  13856. * @param verticesCount defines the count of vertices to draw
  13857. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13858. */
  13859. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13860. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13861. };
  13862. /**
  13863. * Draw a list of indexed primitives
  13864. * @param fillMode defines the primitive to use
  13865. * @param indexStart defines the starting index
  13866. * @param indexCount defines the number of index to draw
  13867. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13868. */
  13869. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13870. // Apply states
  13871. this.applyStates();
  13872. this._drawCalls.addCount(1, false);
  13873. // Render
  13874. var drawMode = this._drawMode(fillMode);
  13875. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13876. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13877. if (instancesCount) {
  13878. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13879. }
  13880. else {
  13881. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13882. }
  13883. };
  13884. /**
  13885. * Draw a list of unindexed primitives
  13886. * @param fillMode defines the primitive to use
  13887. * @param verticesStart defines the index of first vertex to draw
  13888. * @param verticesCount defines the count of vertices to draw
  13889. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13890. */
  13891. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13892. // Apply states
  13893. this.applyStates();
  13894. this._drawCalls.addCount(1, false);
  13895. var drawMode = this._drawMode(fillMode);
  13896. if (instancesCount) {
  13897. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13898. }
  13899. else {
  13900. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13901. }
  13902. };
  13903. Engine.prototype._drawMode = function (fillMode) {
  13904. switch (fillMode) {
  13905. // Triangle views
  13906. case BABYLON.Material.TriangleFillMode:
  13907. return this._gl.TRIANGLES;
  13908. case BABYLON.Material.PointFillMode:
  13909. return this._gl.POINTS;
  13910. case BABYLON.Material.WireFrameFillMode:
  13911. return this._gl.LINES;
  13912. // Draw modes
  13913. case BABYLON.Material.PointListDrawMode:
  13914. return this._gl.POINTS;
  13915. case BABYLON.Material.LineListDrawMode:
  13916. return this._gl.LINES;
  13917. case BABYLON.Material.LineLoopDrawMode:
  13918. return this._gl.LINE_LOOP;
  13919. case BABYLON.Material.LineStripDrawMode:
  13920. return this._gl.LINE_STRIP;
  13921. case BABYLON.Material.TriangleStripDrawMode:
  13922. return this._gl.TRIANGLE_STRIP;
  13923. case BABYLON.Material.TriangleFanDrawMode:
  13924. return this._gl.TRIANGLE_FAN;
  13925. default:
  13926. return this._gl.TRIANGLES;
  13927. }
  13928. };
  13929. // Shaders
  13930. /** @hidden */
  13931. Engine.prototype._releaseEffect = function (effect) {
  13932. if (this._compiledEffects[effect._key]) {
  13933. delete this._compiledEffects[effect._key];
  13934. this._deleteProgram(effect.getProgram());
  13935. }
  13936. };
  13937. /** @hidden */
  13938. Engine.prototype._deleteProgram = function (program) {
  13939. if (program) {
  13940. program.__SPECTOR_rebuildProgram = null;
  13941. if (program.transformFeedback) {
  13942. this.deleteTransformFeedback(program.transformFeedback);
  13943. program.transformFeedback = null;
  13944. }
  13945. this._gl.deleteProgram(program);
  13946. }
  13947. };
  13948. /**
  13949. * Create a new effect (used to store vertex/fragment shaders)
  13950. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13951. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13952. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13953. * @param samplers defines an array of string used to represent textures
  13954. * @param defines defines the string containing the defines to use to compile the shaders
  13955. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13956. * @param onCompiled defines a function to call when the effect creation is successful
  13957. * @param onError defines a function to call when the effect creation has failed
  13958. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13959. * @returns the new Effect
  13960. */
  13961. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13962. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13963. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13964. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13965. if (this._compiledEffects[name]) {
  13966. var compiledEffect = this._compiledEffects[name];
  13967. if (onCompiled && compiledEffect.isReady()) {
  13968. onCompiled(compiledEffect);
  13969. }
  13970. return compiledEffect;
  13971. }
  13972. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13973. effect._key = name;
  13974. this._compiledEffects[name] = effect;
  13975. return effect;
  13976. };
  13977. /**
  13978. * Create an effect to use with particle systems.
  13979. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  13980. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13981. * @param uniformsNames defines a list of attribute names
  13982. * @param samplers defines an array of string used to represent textures
  13983. * @param defines defines the string containing the defines to use to compile the shaders
  13984. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13985. * @param onCompiled defines a function to call when the effect creation is successful
  13986. * @param onError defines a function to call when the effect creation has failed
  13987. * @returns the new Effect
  13988. */
  13989. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13990. if (uniformsNames === void 0) { uniformsNames = []; }
  13991. if (samplers === void 0) { samplers = []; }
  13992. if (defines === void 0) { defines = ""; }
  13993. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  13994. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  13995. if (defines.indexOf(" BILLBOARD") === -1) {
  13996. defines += "\n#define BILLBOARD\n";
  13997. }
  13998. if (samplers.indexOf("diffuseSampler") === -1) {
  13999. samplers.push("diffuseSampler");
  14000. }
  14001. return this.createEffect({
  14002. vertex: "particles",
  14003. fragmentElement: fragmentName
  14004. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  14005. };
  14006. /**
  14007. * Directly creates a webGL program
  14008. * @param vertexCode defines the vertex shader code to use
  14009. * @param fragmentCode defines the fragment shader code to use
  14010. * @param context defines the webGL context to use (if not set, the current one will be used)
  14011. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14012. * @returns the new webGL program
  14013. */
  14014. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14015. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14016. context = context || this._gl;
  14017. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14018. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14019. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14020. };
  14021. /**
  14022. * Creates a webGL program
  14023. * @param vertexCode defines the vertex shader code to use
  14024. * @param fragmentCode defines the fragment shader code to use
  14025. * @param defines defines the string containing the defines to use to compile the shaders
  14026. * @param context defines the webGL context to use (if not set, the current one will be used)
  14027. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14028. * @returns the new webGL program
  14029. */
  14030. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14031. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14032. context = context || this._gl;
  14033. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14034. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14035. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14036. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14037. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14038. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14039. return program;
  14040. };
  14041. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14042. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14043. var shaderProgram = context.createProgram();
  14044. if (!shaderProgram) {
  14045. throw new Error("Unable to create program");
  14046. }
  14047. context.attachShader(shaderProgram, vertexShader);
  14048. context.attachShader(shaderProgram, fragmentShader);
  14049. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14050. var transformFeedback = this.createTransformFeedback();
  14051. this.bindTransformFeedback(transformFeedback);
  14052. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14053. shaderProgram.transformFeedback = transformFeedback;
  14054. }
  14055. context.linkProgram(shaderProgram);
  14056. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14057. this.bindTransformFeedback(null);
  14058. }
  14059. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14060. if (!linked) {
  14061. context.validateProgram(shaderProgram);
  14062. var error = context.getProgramInfoLog(shaderProgram);
  14063. if (error) {
  14064. throw new Error(error);
  14065. }
  14066. }
  14067. context.deleteShader(vertexShader);
  14068. context.deleteShader(fragmentShader);
  14069. return shaderProgram;
  14070. };
  14071. /**
  14072. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14073. * @param shaderProgram defines the webGL program to use
  14074. * @param uniformsNames defines the list of uniform names
  14075. * @returns an array of webGL uniform locations
  14076. */
  14077. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14078. var results = new Array();
  14079. for (var index = 0; index < uniformsNames.length; index++) {
  14080. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14081. }
  14082. return results;
  14083. };
  14084. /**
  14085. * Gets the lsit of active attributes for a given webGL program
  14086. * @param shaderProgram defines the webGL program to use
  14087. * @param attributesNames defines the list of attribute names to get
  14088. * @returns an array of indices indicating the offset of each attribute
  14089. */
  14090. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14091. var results = [];
  14092. for (var index = 0; index < attributesNames.length; index++) {
  14093. try {
  14094. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14095. }
  14096. catch (e) {
  14097. results.push(-1);
  14098. }
  14099. }
  14100. return results;
  14101. };
  14102. /**
  14103. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14104. * @param effect defines the effect to activate
  14105. */
  14106. Engine.prototype.enableEffect = function (effect) {
  14107. if (!effect) {
  14108. return;
  14109. }
  14110. // Use program
  14111. this.bindSamplers(effect);
  14112. this._currentEffect = effect;
  14113. if (effect.onBind) {
  14114. effect.onBind(effect);
  14115. }
  14116. effect.onBindObservable.notifyObservers(effect);
  14117. };
  14118. /**
  14119. * Set the value of an uniform to an array of int32
  14120. * @param uniform defines the webGL uniform location where to store the value
  14121. * @param array defines the array of int32 to store
  14122. */
  14123. Engine.prototype.setIntArray = function (uniform, array) {
  14124. if (!uniform)
  14125. return;
  14126. this._gl.uniform1iv(uniform, array);
  14127. };
  14128. /**
  14129. * Set the value of an uniform to an array of int32 (stored as vec2)
  14130. * @param uniform defines the webGL uniform location where to store the value
  14131. * @param array defines the array of int32 to store
  14132. */
  14133. Engine.prototype.setIntArray2 = function (uniform, array) {
  14134. if (!uniform || array.length % 2 !== 0)
  14135. return;
  14136. this._gl.uniform2iv(uniform, array);
  14137. };
  14138. /**
  14139. * Set the value of an uniform to an array of int32 (stored as vec3)
  14140. * @param uniform defines the webGL uniform location where to store the value
  14141. * @param array defines the array of int32 to store
  14142. */
  14143. Engine.prototype.setIntArray3 = function (uniform, array) {
  14144. if (!uniform || array.length % 3 !== 0)
  14145. return;
  14146. this._gl.uniform3iv(uniform, array);
  14147. };
  14148. /**
  14149. * Set the value of an uniform to an array of int32 (stored as vec4)
  14150. * @param uniform defines the webGL uniform location where to store the value
  14151. * @param array defines the array of int32 to store
  14152. */
  14153. Engine.prototype.setIntArray4 = function (uniform, array) {
  14154. if (!uniform || array.length % 4 !== 0)
  14155. return;
  14156. this._gl.uniform4iv(uniform, array);
  14157. };
  14158. /**
  14159. * Set the value of an uniform to an array of float32
  14160. * @param uniform defines the webGL uniform location where to store the value
  14161. * @param array defines the array of float32 to store
  14162. */
  14163. Engine.prototype.setFloatArray = function (uniform, array) {
  14164. if (!uniform)
  14165. return;
  14166. this._gl.uniform1fv(uniform, array);
  14167. };
  14168. /**
  14169. * Set the value of an uniform to an array of float32 (stored as vec2)
  14170. * @param uniform defines the webGL uniform location where to store the value
  14171. * @param array defines the array of float32 to store
  14172. */
  14173. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14174. if (!uniform || array.length % 2 !== 0)
  14175. return;
  14176. this._gl.uniform2fv(uniform, array);
  14177. };
  14178. /**
  14179. * Set the value of an uniform to an array of float32 (stored as vec3)
  14180. * @param uniform defines the webGL uniform location where to store the value
  14181. * @param array defines the array of float32 to store
  14182. */
  14183. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14184. if (!uniform || array.length % 3 !== 0)
  14185. return;
  14186. this._gl.uniform3fv(uniform, array);
  14187. };
  14188. /**
  14189. * Set the value of an uniform to an array of float32 (stored as vec4)
  14190. * @param uniform defines the webGL uniform location where to store the value
  14191. * @param array defines the array of float32 to store
  14192. */
  14193. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14194. if (!uniform || array.length % 4 !== 0)
  14195. return;
  14196. this._gl.uniform4fv(uniform, array);
  14197. };
  14198. /**
  14199. * Set the value of an uniform to an array of number
  14200. * @param uniform defines the webGL uniform location where to store the value
  14201. * @param array defines the array of number to store
  14202. */
  14203. Engine.prototype.setArray = function (uniform, array) {
  14204. if (!uniform)
  14205. return;
  14206. this._gl.uniform1fv(uniform, array);
  14207. };
  14208. /**
  14209. * Set the value of an uniform to an array of number (stored as vec2)
  14210. * @param uniform defines the webGL uniform location where to store the value
  14211. * @param array defines the array of number to store
  14212. */
  14213. Engine.prototype.setArray2 = function (uniform, array) {
  14214. if (!uniform || array.length % 2 !== 0)
  14215. return;
  14216. this._gl.uniform2fv(uniform, array);
  14217. };
  14218. /**
  14219. * Set the value of an uniform to an array of number (stored as vec3)
  14220. * @param uniform defines the webGL uniform location where to store the value
  14221. * @param array defines the array of number to store
  14222. */
  14223. Engine.prototype.setArray3 = function (uniform, array) {
  14224. if (!uniform || array.length % 3 !== 0)
  14225. return;
  14226. this._gl.uniform3fv(uniform, array);
  14227. };
  14228. /**
  14229. * Set the value of an uniform to an array of number (stored as vec4)
  14230. * @param uniform defines the webGL uniform location where to store the value
  14231. * @param array defines the array of number to store
  14232. */
  14233. Engine.prototype.setArray4 = function (uniform, array) {
  14234. if (!uniform || array.length % 4 !== 0)
  14235. return;
  14236. this._gl.uniform4fv(uniform, array);
  14237. };
  14238. /**
  14239. * Set the value of an uniform to an array of float32 (stored as matrices)
  14240. * @param uniform defines the webGL uniform location where to store the value
  14241. * @param matrices defines the array of float32 to store
  14242. */
  14243. Engine.prototype.setMatrices = function (uniform, matrices) {
  14244. if (!uniform)
  14245. return;
  14246. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14247. };
  14248. /**
  14249. * Set the value of an uniform to a matrix
  14250. * @param uniform defines the webGL uniform location where to store the value
  14251. * @param matrix defines the matrix to store
  14252. */
  14253. Engine.prototype.setMatrix = function (uniform, matrix) {
  14254. if (!uniform)
  14255. return;
  14256. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14257. };
  14258. /**
  14259. * Set the value of an uniform to a matrix (3x3)
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14262. */
  14263. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14264. if (!uniform)
  14265. return;
  14266. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14267. };
  14268. /**
  14269. * Set the value of an uniform to a matrix (2x2)
  14270. * @param uniform defines the webGL uniform location where to store the value
  14271. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14272. */
  14273. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14274. if (!uniform)
  14275. return;
  14276. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14277. };
  14278. /**
  14279. * Set the value of an uniform to a number (int)
  14280. * @param uniform defines the webGL uniform location where to store the value
  14281. * @param value defines the int number to store
  14282. */
  14283. Engine.prototype.setInt = function (uniform, value) {
  14284. if (!uniform)
  14285. return;
  14286. this._gl.uniform1i(uniform, value);
  14287. };
  14288. /**
  14289. * Set the value of an uniform to a number (float)
  14290. * @param uniform defines the webGL uniform location where to store the value
  14291. * @param value defines the float number to store
  14292. */
  14293. Engine.prototype.setFloat = function (uniform, value) {
  14294. if (!uniform)
  14295. return;
  14296. this._gl.uniform1f(uniform, value);
  14297. };
  14298. /**
  14299. * Set the value of an uniform to a vec2
  14300. * @param uniform defines the webGL uniform location where to store the value
  14301. * @param x defines the 1st component of the value
  14302. * @param y defines the 2nd component of the value
  14303. */
  14304. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14305. if (!uniform)
  14306. return;
  14307. this._gl.uniform2f(uniform, x, y);
  14308. };
  14309. /**
  14310. * Set the value of an uniform to a vec3
  14311. * @param uniform defines the webGL uniform location where to store the value
  14312. * @param x defines the 1st component of the value
  14313. * @param y defines the 2nd component of the value
  14314. * @param z defines the 3rd component of the value
  14315. */
  14316. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14317. if (!uniform)
  14318. return;
  14319. this._gl.uniform3f(uniform, x, y, z);
  14320. };
  14321. /**
  14322. * Set the value of an uniform to a boolean
  14323. * @param uniform defines the webGL uniform location where to store the value
  14324. * @param bool defines the boolean to store
  14325. */
  14326. Engine.prototype.setBool = function (uniform, bool) {
  14327. if (!uniform)
  14328. return;
  14329. this._gl.uniform1i(uniform, bool);
  14330. };
  14331. /**
  14332. * Set the value of an uniform to a vec4
  14333. * @param uniform defines the webGL uniform location where to store the value
  14334. * @param x defines the 1st component of the value
  14335. * @param y defines the 2nd component of the value
  14336. * @param z defines the 3rd component of the value
  14337. * @param w defines the 4th component of the value
  14338. */
  14339. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14340. if (!uniform)
  14341. return;
  14342. this._gl.uniform4f(uniform, x, y, z, w);
  14343. };
  14344. /**
  14345. * Set the value of an uniform to a Color3
  14346. * @param uniform defines the webGL uniform location where to store the value
  14347. * @param color3 defines the color to store
  14348. */
  14349. Engine.prototype.setColor3 = function (uniform, color3) {
  14350. if (!uniform)
  14351. return;
  14352. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14353. };
  14354. /**
  14355. * Set the value of an uniform to a Color3 and an alpha value
  14356. * @param uniform defines the webGL uniform location where to store the value
  14357. * @param color3 defines the color to store
  14358. * @param alpha defines the alpha component to store
  14359. */
  14360. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14361. if (!uniform)
  14362. return;
  14363. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14364. };
  14365. /**
  14366. * Sets a Color4 on a uniform variable
  14367. * @param uniform defines the uniform location
  14368. * @param color4 defines the value to be set
  14369. */
  14370. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14371. if (!uniform)
  14372. return;
  14373. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14374. };
  14375. // States
  14376. /**
  14377. * Set various states to the webGL context
  14378. * @param culling defines backface culling state
  14379. * @param zOffset defines the value to apply to zOffset (0 by default)
  14380. * @param force defines if states must be applied even if cache is up to date
  14381. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14382. */
  14383. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14384. if (zOffset === void 0) { zOffset = 0; }
  14385. if (reverseSide === void 0) { reverseSide = false; }
  14386. // Culling
  14387. if (this._depthCullingState.cull !== culling || force) {
  14388. this._depthCullingState.cull = culling;
  14389. }
  14390. // Cull face
  14391. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14392. if (this._depthCullingState.cullFace !== cullFace || force) {
  14393. this._depthCullingState.cullFace = cullFace;
  14394. }
  14395. // Z offset
  14396. this.setZOffset(zOffset);
  14397. // Front face
  14398. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14399. if (this._depthCullingState.frontFace !== frontFace || force) {
  14400. this._depthCullingState.frontFace = frontFace;
  14401. }
  14402. };
  14403. /**
  14404. * Set the z offset to apply to current rendering
  14405. * @param value defines the offset to apply
  14406. */
  14407. Engine.prototype.setZOffset = function (value) {
  14408. this._depthCullingState.zOffset = value;
  14409. };
  14410. /**
  14411. * Gets the current value of the zOffset
  14412. * @returns the current zOffset state
  14413. */
  14414. Engine.prototype.getZOffset = function () {
  14415. return this._depthCullingState.zOffset;
  14416. };
  14417. /**
  14418. * Enable or disable depth buffering
  14419. * @param enable defines the state to set
  14420. */
  14421. Engine.prototype.setDepthBuffer = function (enable) {
  14422. this._depthCullingState.depthTest = enable;
  14423. };
  14424. /**
  14425. * Gets a boolean indicating if depth writing is enabled
  14426. * @returns the current depth writing state
  14427. */
  14428. Engine.prototype.getDepthWrite = function () {
  14429. return this._depthCullingState.depthMask;
  14430. };
  14431. /**
  14432. * Enable or disable depth writing
  14433. * @param enable defines the state to set
  14434. */
  14435. Engine.prototype.setDepthWrite = function (enable) {
  14436. this._depthCullingState.depthMask = enable;
  14437. };
  14438. /**
  14439. * Enable or disable color writing
  14440. * @param enable defines the state to set
  14441. */
  14442. Engine.prototype.setColorWrite = function (enable) {
  14443. this._gl.colorMask(enable, enable, enable, enable);
  14444. this._colorWrite = enable;
  14445. };
  14446. /**
  14447. * Gets a boolean indicating if color writing is enabled
  14448. * @returns the current color writing state
  14449. */
  14450. Engine.prototype.getColorWrite = function () {
  14451. return this._colorWrite;
  14452. };
  14453. /**
  14454. * Sets alpha constants used by some alpha blending modes
  14455. * @param r defines the red component
  14456. * @param g defines the green component
  14457. * @param b defines the blue component
  14458. * @param a defines the alpha component
  14459. */
  14460. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14461. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14462. };
  14463. /**
  14464. * Sets the current alpha mode
  14465. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14466. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14467. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14468. */
  14469. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14470. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14471. if (this._alphaMode === mode) {
  14472. return;
  14473. }
  14474. switch (mode) {
  14475. case Engine.ALPHA_DISABLE:
  14476. this._alphaState.alphaBlend = false;
  14477. break;
  14478. case Engine.ALPHA_PREMULTIPLIED:
  14479. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14480. this._alphaState.alphaBlend = true;
  14481. break;
  14482. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14483. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14484. this._alphaState.alphaBlend = true;
  14485. break;
  14486. case Engine.ALPHA_COMBINE:
  14487. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14488. this._alphaState.alphaBlend = true;
  14489. break;
  14490. case Engine.ALPHA_ONEONE:
  14491. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14492. this._alphaState.alphaBlend = true;
  14493. break;
  14494. case Engine.ALPHA_ADD:
  14495. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14496. this._alphaState.alphaBlend = true;
  14497. break;
  14498. case Engine.ALPHA_SUBTRACT:
  14499. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14500. this._alphaState.alphaBlend = true;
  14501. break;
  14502. case Engine.ALPHA_MULTIPLY:
  14503. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14504. this._alphaState.alphaBlend = true;
  14505. break;
  14506. case Engine.ALPHA_MAXIMIZED:
  14507. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14508. this._alphaState.alphaBlend = true;
  14509. break;
  14510. case Engine.ALPHA_INTERPOLATE:
  14511. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14512. this._alphaState.alphaBlend = true;
  14513. break;
  14514. case Engine.ALPHA_SCREENMODE:
  14515. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14516. this._alphaState.alphaBlend = true;
  14517. break;
  14518. }
  14519. if (!noDepthWriteChange) {
  14520. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14521. }
  14522. this._alphaMode = mode;
  14523. };
  14524. /**
  14525. * Gets the current alpha mode
  14526. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14527. * @returns the current alpha mode
  14528. */
  14529. Engine.prototype.getAlphaMode = function () {
  14530. return this._alphaMode;
  14531. };
  14532. // Textures
  14533. /**
  14534. * Clears the list of texture accessible through engine.
  14535. * This can help preventing texture load conflict due to name collision.
  14536. */
  14537. Engine.prototype.clearInternalTexturesCache = function () {
  14538. this._internalTexturesCache = [];
  14539. };
  14540. /**
  14541. * Force the entire cache to be cleared
  14542. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14543. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14544. */
  14545. Engine.prototype.wipeCaches = function (bruteForce) {
  14546. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14547. return;
  14548. }
  14549. this._currentEffect = null;
  14550. this._unpackFlipYCached = null;
  14551. this._viewportCached.x = 0;
  14552. this._viewportCached.y = 0;
  14553. this._viewportCached.z = 0;
  14554. this._viewportCached.w = 0;
  14555. if (bruteForce) {
  14556. this.resetTextureCache();
  14557. this._currentProgram = null;
  14558. this._stencilState.reset();
  14559. this._depthCullingState.reset();
  14560. this.setDepthFunctionToLessOrEqual();
  14561. this._alphaState.reset();
  14562. }
  14563. this._resetVertexBufferBinding();
  14564. this._cachedIndexBuffer = null;
  14565. this._cachedEffectForVertexBuffers = null;
  14566. this._unbindVertexArrayObject();
  14567. this.bindIndexBuffer(null);
  14568. };
  14569. /**
  14570. * Set the compressed texture format to use, based on the formats you have, and the formats
  14571. * supported by the hardware / browser.
  14572. *
  14573. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14574. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14575. * to API arguments needed to compressed textures. This puts the burden on the container
  14576. * generator to house the arcane code for determining these for current & future formats.
  14577. *
  14578. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14579. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14580. *
  14581. * Note: The result of this call is not taken into account when a texture is base64.
  14582. *
  14583. * @param formatsAvailable defines the list of those format families you have created
  14584. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14585. *
  14586. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14587. * @returns The extension selected.
  14588. */
  14589. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14590. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14591. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14592. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14593. return this._textureFormatInUse = this._texturesSupported[i];
  14594. }
  14595. }
  14596. }
  14597. // actively set format to nothing, to allow this to be called more than once
  14598. // and possibly fail the 2nd time
  14599. this._textureFormatInUse = null;
  14600. return null;
  14601. };
  14602. /** @hidden */
  14603. Engine.prototype._createTexture = function () {
  14604. var texture = this._gl.createTexture();
  14605. if (!texture) {
  14606. throw new Error("Unable to create texture");
  14607. }
  14608. return texture;
  14609. };
  14610. /**
  14611. * Usually called from BABYLON.Texture.ts.
  14612. * Passed information to create a WebGLTexture
  14613. * @param urlArg defines a value which contains one of the following:
  14614. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14615. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14616. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14617. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14618. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14619. * @param scene needed for loading to the correct scene
  14620. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14621. * @param onLoad optional callback to be called upon successful completion
  14622. * @param onError optional callback to be called upon failure
  14623. * @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
  14624. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14625. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14626. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14627. */
  14628. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14629. var _this = this;
  14630. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14631. if (onLoad === void 0) { onLoad = null; }
  14632. if (onError === void 0) { onError = null; }
  14633. if (buffer === void 0) { buffer = null; }
  14634. if (fallback === void 0) { fallback = null; }
  14635. if (format === void 0) { format = null; }
  14636. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14637. var fromData = url.substr(0, 5) === "data:";
  14638. var fromBlob = url.substr(0, 5) === "blob:";
  14639. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14640. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14641. // establish the file extension, if possible
  14642. var lastDot = url.lastIndexOf('.');
  14643. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14644. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14645. var isTGA = (extension.indexOf(".tga") === 0);
  14646. // determine if a ktx file should be substituted
  14647. var isKTX = false;
  14648. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14649. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14650. isKTX = true;
  14651. }
  14652. if (scene) {
  14653. scene._addPendingData(texture);
  14654. }
  14655. texture.url = url;
  14656. texture.generateMipMaps = !noMipmap;
  14657. texture.samplingMode = samplingMode;
  14658. texture.invertY = invertY;
  14659. if (!this._doNotHandleContextLost) {
  14660. // Keep a link to the buffer only if we plan to handle context lost
  14661. texture._buffer = buffer;
  14662. }
  14663. var onLoadObserver = null;
  14664. if (onLoad && !fallback) {
  14665. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14666. }
  14667. if (!fallback)
  14668. this._internalTexturesCache.push(texture);
  14669. var onerror = function (message, exception) {
  14670. if (scene) {
  14671. scene._removePendingData(texture);
  14672. }
  14673. if (onLoadObserver && !isKTX) {
  14674. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14675. texture.onLoadedObservable.remove(onLoadObserver);
  14676. }
  14677. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14678. if (isKTX) {
  14679. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14680. }
  14681. else if (BABYLON.Tools.UseFallbackTexture) {
  14682. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14683. }
  14684. if (onError) {
  14685. onError(message || "Unknown error", exception);
  14686. }
  14687. };
  14688. var callback = null;
  14689. // processing for non-image formats
  14690. if (isKTX || isTGA || isDDS) {
  14691. if (isKTX) {
  14692. callback = function (data) {
  14693. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14694. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14695. ktx.uploadLevels(_this._gl, !noMipmap);
  14696. return false;
  14697. }, samplingMode);
  14698. };
  14699. }
  14700. else if (isTGA) {
  14701. callback = function (arrayBuffer) {
  14702. var data = new Uint8Array(arrayBuffer);
  14703. var header = BABYLON.TGATools.GetTGAHeader(data);
  14704. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14705. BABYLON.TGATools.UploadContent(_this._gl, data);
  14706. return false;
  14707. }, samplingMode);
  14708. };
  14709. }
  14710. else if (isDDS) {
  14711. callback = function (data) {
  14712. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14713. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14714. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14715. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14716. return false;
  14717. }, samplingMode);
  14718. };
  14719. }
  14720. if (!buffer) {
  14721. this._loadFile(url, function (data) {
  14722. if (callback) {
  14723. callback(data);
  14724. }
  14725. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14726. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14727. });
  14728. }
  14729. else {
  14730. if (callback) {
  14731. callback(buffer);
  14732. }
  14733. }
  14734. // image format processing
  14735. }
  14736. else {
  14737. var onload = function (img) {
  14738. if (fromBlob && !_this._doNotHandleContextLost) {
  14739. // We need to store the image if we need to rebuild the texture
  14740. // in case of a webgl context lost
  14741. texture._buffer = img;
  14742. }
  14743. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14744. var gl = _this._gl;
  14745. var isPot = (img.width === potWidth && img.height === potHeight);
  14746. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14747. if (isPot) {
  14748. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14749. return false;
  14750. }
  14751. var maxTextureSize = _this._caps.maxTextureSize;
  14752. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14753. _this._prepareWorkingCanvas();
  14754. if (!_this._workingCanvas || !_this._workingContext) {
  14755. return false;
  14756. }
  14757. _this._workingCanvas.width = potWidth;
  14758. _this._workingCanvas.height = potHeight;
  14759. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14760. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14761. texture.width = potWidth;
  14762. texture.height = potHeight;
  14763. return false;
  14764. }
  14765. else {
  14766. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14767. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14768. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14769. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14770. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14771. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14772. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14773. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14774. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14775. _this._releaseTexture(source_1);
  14776. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14777. continuationCallback();
  14778. });
  14779. }
  14780. return true;
  14781. }, samplingMode);
  14782. };
  14783. if (!fromData || isBase64) {
  14784. if (buffer instanceof HTMLImageElement) {
  14785. onload(buffer);
  14786. }
  14787. else {
  14788. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14789. }
  14790. }
  14791. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14792. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14793. }
  14794. else {
  14795. onload(buffer);
  14796. }
  14797. }
  14798. return texture;
  14799. };
  14800. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14801. var _this = this;
  14802. var rtt = this.createRenderTargetTexture({
  14803. width: destination.width,
  14804. height: destination.height,
  14805. }, {
  14806. generateMipMaps: false,
  14807. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14808. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14809. generateDepthBuffer: false,
  14810. generateStencilBuffer: false
  14811. });
  14812. if (!this._rescalePostProcess) {
  14813. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14814. }
  14815. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14816. _this._rescalePostProcess.onApply = function (effect) {
  14817. effect._bindTexture("textureSampler", source);
  14818. };
  14819. var hostingScene = scene;
  14820. if (!hostingScene) {
  14821. hostingScene = _this.scenes[_this.scenes.length - 1];
  14822. }
  14823. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14824. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14825. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14826. _this.unBindFramebuffer(rtt);
  14827. _this._releaseTexture(rtt);
  14828. if (onComplete) {
  14829. onComplete();
  14830. }
  14831. });
  14832. };
  14833. /**
  14834. * Update a raw texture
  14835. * @param texture defines the texture to update
  14836. * @param data defines the data to store in the texture
  14837. * @param format defines the format of the data
  14838. * @param invertY defines if data must be stored with Y axis inverted
  14839. * @param compression defines the compression used (null by default)
  14840. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14841. */
  14842. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14843. if (compression === void 0) { compression = null; }
  14844. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14845. if (!texture) {
  14846. return;
  14847. }
  14848. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14849. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14850. // babylon's internalFormat but gl's texImage2D format
  14851. var internalFormat = this._getInternalFormat(format);
  14852. var textureType = this._getWebGLTextureType(type);
  14853. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14854. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14855. if (!this._doNotHandleContextLost) {
  14856. texture._bufferView = data;
  14857. texture.format = format;
  14858. texture.type = type;
  14859. texture.invertY = invertY;
  14860. texture._compression = compression;
  14861. }
  14862. if (texture.width % 4 !== 0) {
  14863. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14864. }
  14865. if (compression && data) {
  14866. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14867. }
  14868. else {
  14869. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14870. }
  14871. if (texture.generateMipMaps) {
  14872. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14873. }
  14874. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14875. // this.resetTextureCache();
  14876. texture.isReady = true;
  14877. };
  14878. /**
  14879. * Creates a raw texture
  14880. * @param data defines the data to store in the texture
  14881. * @param width defines the width of the texture
  14882. * @param height defines the height of the texture
  14883. * @param format defines the format of the data
  14884. * @param generateMipMaps defines if the engine should generate the mip levels
  14885. * @param invertY defines if data must be stored with Y axis inverted
  14886. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14887. * @param compression defines the compression used (null by default)
  14888. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14889. * @returns the raw texture inside an InternalTexture
  14890. */
  14891. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14892. if (compression === void 0) { compression = null; }
  14893. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14894. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14895. texture.baseWidth = width;
  14896. texture.baseHeight = height;
  14897. texture.width = width;
  14898. texture.height = height;
  14899. texture.format = format;
  14900. texture.generateMipMaps = generateMipMaps;
  14901. texture.samplingMode = samplingMode;
  14902. texture.invertY = invertY;
  14903. texture._compression = compression;
  14904. texture.type = type;
  14905. if (!this._doNotHandleContextLost) {
  14906. texture._bufferView = data;
  14907. }
  14908. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14909. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14910. // Filters
  14911. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14914. if (generateMipMaps) {
  14915. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14916. }
  14917. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14918. this._internalTexturesCache.push(texture);
  14919. return texture;
  14920. };
  14921. /** @hidden */
  14922. Engine.prototype._unpackFlipY = function (value) {
  14923. if (this._unpackFlipYCached !== value) {
  14924. this._unpackFlipYCached = value;
  14925. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14926. }
  14927. };
  14928. /**
  14929. * Creates a dynamic texture
  14930. * @param width defines the width of the texture
  14931. * @param height defines the height of the texture
  14932. * @param generateMipMaps defines if the engine should generate the mip levels
  14933. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14934. * @returns the dynamic texture inside an InternalTexture
  14935. */
  14936. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14937. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14938. texture.baseWidth = width;
  14939. texture.baseHeight = height;
  14940. if (generateMipMaps) {
  14941. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14942. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14943. }
  14944. // this.resetTextureCache();
  14945. texture.width = width;
  14946. texture.height = height;
  14947. texture.isReady = false;
  14948. texture.generateMipMaps = generateMipMaps;
  14949. texture.samplingMode = samplingMode;
  14950. this.updateTextureSamplingMode(samplingMode, texture);
  14951. this._internalTexturesCache.push(texture);
  14952. return texture;
  14953. };
  14954. /**
  14955. * Update the sampling mode of a given texture
  14956. * @param samplingMode defines the required sampling mode
  14957. * @param texture defines the texture to update
  14958. */
  14959. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14960. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14961. if (texture.isCube) {
  14962. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14963. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14964. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14965. }
  14966. else if (texture.is3D) {
  14967. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14968. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14969. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14970. }
  14971. else {
  14972. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14973. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14974. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14975. }
  14976. texture.samplingMode = samplingMode;
  14977. };
  14978. /**
  14979. * Update the content of a dynamic texture
  14980. * @param texture defines the texture to update
  14981. * @param canvas defines the canvas containing the source
  14982. * @param invertY defines if data must be stored with Y axis inverted
  14983. * @param premulAlpha defines if alpha is stored as premultiplied
  14984. * @param format defines the format of the data
  14985. */
  14986. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14987. if (premulAlpha === void 0) { premulAlpha = false; }
  14988. if (!texture) {
  14989. return;
  14990. }
  14991. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14992. this._unpackFlipY(invertY);
  14993. if (premulAlpha) {
  14994. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14995. }
  14996. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14997. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14998. if (texture.generateMipMaps) {
  14999. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15000. }
  15001. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15002. if (premulAlpha) {
  15003. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15004. }
  15005. texture.isReady = true;
  15006. };
  15007. /**
  15008. * Update a video texture
  15009. * @param texture defines the texture to update
  15010. * @param video defines the video element to use
  15011. * @param invertY defines if data must be stored with Y axis inverted
  15012. */
  15013. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15014. if (!texture || texture._isDisabled) {
  15015. return;
  15016. }
  15017. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15018. this._unpackFlipY(!invertY); // Video are upside down by default
  15019. try {
  15020. // Testing video texture support
  15021. if (this._videoTextureSupported === undefined) {
  15022. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15023. if (this._gl.getError() !== 0) {
  15024. this._videoTextureSupported = false;
  15025. }
  15026. else {
  15027. this._videoTextureSupported = true;
  15028. }
  15029. }
  15030. // Copy video through the current working canvas if video texture is not supported
  15031. if (!this._videoTextureSupported) {
  15032. if (!texture._workingCanvas) {
  15033. texture._workingCanvas = document.createElement("canvas");
  15034. var context = texture._workingCanvas.getContext("2d");
  15035. if (!context) {
  15036. throw new Error("Unable to get 2d context");
  15037. }
  15038. texture._workingContext = context;
  15039. texture._workingCanvas.width = texture.width;
  15040. texture._workingCanvas.height = texture.height;
  15041. }
  15042. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15043. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15044. }
  15045. else {
  15046. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15047. }
  15048. if (texture.generateMipMaps) {
  15049. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15050. }
  15051. if (!wasPreviouslyBound) {
  15052. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15053. }
  15054. // this.resetTextureCache();
  15055. texture.isReady = true;
  15056. }
  15057. catch (ex) {
  15058. // Something unexpected
  15059. // Let's disable the texture
  15060. texture._isDisabled = true;
  15061. }
  15062. };
  15063. /**
  15064. * Updates a depth texture Comparison Mode and Function.
  15065. * If the comparison Function is equal to 0, the mode will be set to none.
  15066. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15067. * @param texture The texture to set the comparison function for
  15068. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15069. */
  15070. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15071. if (this.webGLVersion === 1) {
  15072. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15073. return;
  15074. }
  15075. var gl = this._gl;
  15076. if (texture.isCube) {
  15077. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15078. if (comparisonFunction === 0) {
  15079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15080. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15081. }
  15082. else {
  15083. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15084. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15085. }
  15086. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15087. }
  15088. else {
  15089. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15090. if (comparisonFunction === 0) {
  15091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15093. }
  15094. else {
  15095. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15096. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15097. }
  15098. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15099. }
  15100. texture._comparisonFunction = comparisonFunction;
  15101. };
  15102. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15103. var width = size.width || size;
  15104. var height = size.height || size;
  15105. internalTexture.baseWidth = width;
  15106. internalTexture.baseHeight = height;
  15107. internalTexture.width = width;
  15108. internalTexture.height = height;
  15109. internalTexture.isReady = true;
  15110. internalTexture.samples = 1;
  15111. internalTexture.generateMipMaps = false;
  15112. internalTexture._generateDepthBuffer = true;
  15113. internalTexture._generateStencilBuffer = generateStencil;
  15114. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15115. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15116. internalTexture._comparisonFunction = comparisonFunction;
  15117. var gl = this._gl;
  15118. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15119. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15120. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15121. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15122. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15123. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15124. if (comparisonFunction === 0) {
  15125. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15126. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15127. }
  15128. else {
  15129. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15130. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15131. }
  15132. };
  15133. /**
  15134. * Creates a depth stencil texture.
  15135. * This is only available in WebGL 2 or with the depth texture extension available.
  15136. * @param size The size of face edge in the texture.
  15137. * @param options The options defining the texture.
  15138. * @returns The texture
  15139. */
  15140. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15141. if (options.isCube) {
  15142. var width = size.width || size;
  15143. return this._createDepthStencilCubeTexture(width, options);
  15144. }
  15145. else {
  15146. return this._createDepthStencilTexture(size, options);
  15147. }
  15148. };
  15149. /**
  15150. * Creates a depth stencil texture.
  15151. * This is only available in WebGL 2 or with the depth texture extension available.
  15152. * @param size The size of face edge in the texture.
  15153. * @param options The options defining the texture.
  15154. * @returns The texture
  15155. */
  15156. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15157. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15158. if (!this._caps.depthTextureExtension) {
  15159. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15160. return internalTexture;
  15161. }
  15162. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15163. var gl = this._gl;
  15164. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15165. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15166. if (this.webGLVersion > 1) {
  15167. if (internalOptions.generateStencil) {
  15168. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15169. }
  15170. else {
  15171. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15172. }
  15173. }
  15174. else {
  15175. if (internalOptions.generateStencil) {
  15176. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15177. }
  15178. else {
  15179. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15180. }
  15181. }
  15182. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15183. return internalTexture;
  15184. };
  15185. /**
  15186. * Creates a depth stencil cube texture.
  15187. * This is only available in WebGL 2.
  15188. * @param size The size of face edge in the cube texture.
  15189. * @param options The options defining the cube texture.
  15190. * @returns The cube texture
  15191. */
  15192. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15193. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15194. internalTexture.isCube = true;
  15195. if (this.webGLVersion === 1) {
  15196. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15197. return internalTexture;
  15198. }
  15199. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15200. var gl = this._gl;
  15201. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15202. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15203. // Create the depth/stencil buffer
  15204. for (var face = 0; face < 6; face++) {
  15205. if (internalOptions.generateStencil) {
  15206. 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);
  15207. }
  15208. else {
  15209. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15210. }
  15211. }
  15212. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15213. return internalTexture;
  15214. };
  15215. /**
  15216. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15217. * @param renderTarget The render target to set the frame buffer for
  15218. */
  15219. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15220. // Create the framebuffer
  15221. var internalTexture = renderTarget.getInternalTexture();
  15222. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15223. return;
  15224. }
  15225. var gl = this._gl;
  15226. var depthStencilTexture = renderTarget.depthStencilTexture;
  15227. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15228. if (depthStencilTexture.isCube) {
  15229. if (depthStencilTexture._generateStencilBuffer) {
  15230. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15231. }
  15232. else {
  15233. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15234. }
  15235. }
  15236. else {
  15237. if (depthStencilTexture._generateStencilBuffer) {
  15238. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15239. }
  15240. else {
  15241. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15242. }
  15243. }
  15244. this.bindUnboundFramebuffer(null);
  15245. };
  15246. /**
  15247. * Creates a new render target texture
  15248. * @param size defines the size of the texture
  15249. * @param options defines the options used to create the texture
  15250. * @returns a new render target texture stored in an InternalTexture
  15251. */
  15252. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15253. var fullOptions = new RenderTargetCreationOptions();
  15254. if (options !== undefined && typeof options === "object") {
  15255. fullOptions.generateMipMaps = options.generateMipMaps;
  15256. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15257. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15258. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15259. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15260. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15261. }
  15262. else {
  15263. fullOptions.generateMipMaps = options;
  15264. fullOptions.generateDepthBuffer = true;
  15265. fullOptions.generateStencilBuffer = false;
  15266. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15267. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15268. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15269. }
  15270. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15271. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15272. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15273. }
  15274. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15275. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15276. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15277. }
  15278. var gl = this._gl;
  15279. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15280. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15281. var width = size.width || size;
  15282. var height = size.height || size;
  15283. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15284. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15285. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15286. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15287. }
  15288. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15289. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15291. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15292. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15293. // Create the framebuffer
  15294. var currentFrameBuffer = this._currentFramebuffer;
  15295. var framebuffer = gl.createFramebuffer();
  15296. this.bindUnboundFramebuffer(framebuffer);
  15297. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15298. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15299. if (fullOptions.generateMipMaps) {
  15300. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15301. }
  15302. // Unbind
  15303. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15304. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15305. this.bindUnboundFramebuffer(currentFrameBuffer);
  15306. texture._framebuffer = framebuffer;
  15307. texture.baseWidth = width;
  15308. texture.baseHeight = height;
  15309. texture.width = width;
  15310. texture.height = height;
  15311. texture.isReady = true;
  15312. texture.samples = 1;
  15313. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15314. texture.samplingMode = fullOptions.samplingMode;
  15315. texture.type = fullOptions.type;
  15316. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15317. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15318. // this.resetTextureCache();
  15319. this._internalTexturesCache.push(texture);
  15320. return texture;
  15321. };
  15322. /**
  15323. * Create a multi render target texture
  15324. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15325. * @param size defines the size of the texture
  15326. * @param options defines the creation options
  15327. * @returns the cube texture as an InternalTexture
  15328. */
  15329. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15330. var generateMipMaps = false;
  15331. var generateDepthBuffer = true;
  15332. var generateStencilBuffer = false;
  15333. var generateDepthTexture = false;
  15334. var textureCount = 1;
  15335. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15336. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15337. var types = new Array();
  15338. var samplingModes = new Array();
  15339. if (options !== undefined) {
  15340. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15341. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15342. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15343. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15344. textureCount = options.textureCount || 1;
  15345. if (options.types) {
  15346. types = options.types;
  15347. }
  15348. if (options.samplingModes) {
  15349. samplingModes = options.samplingModes;
  15350. }
  15351. }
  15352. var gl = this._gl;
  15353. // Create the framebuffer
  15354. var framebuffer = gl.createFramebuffer();
  15355. this.bindUnboundFramebuffer(framebuffer);
  15356. var width = size.width || size;
  15357. var height = size.height || size;
  15358. var textures = [];
  15359. var attachments = [];
  15360. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15361. for (var i = 0; i < textureCount; i++) {
  15362. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15363. var type = types[i] || defaultType;
  15364. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15365. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15366. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15367. }
  15368. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15369. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15370. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15371. }
  15372. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15373. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15374. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15375. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15376. }
  15377. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15378. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15379. textures.push(texture);
  15380. attachments.push(attachment);
  15381. gl.activeTexture(gl["TEXTURE" + i]);
  15382. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15383. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15384. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15385. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15386. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15387. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15388. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15389. if (generateMipMaps) {
  15390. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15391. }
  15392. // Unbind
  15393. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15394. texture._framebuffer = framebuffer;
  15395. texture._depthStencilBuffer = depthStencilBuffer;
  15396. texture.baseWidth = width;
  15397. texture.baseHeight = height;
  15398. texture.width = width;
  15399. texture.height = height;
  15400. texture.isReady = true;
  15401. texture.samples = 1;
  15402. texture.generateMipMaps = generateMipMaps;
  15403. texture.samplingMode = samplingMode;
  15404. texture.type = type;
  15405. texture._generateDepthBuffer = generateDepthBuffer;
  15406. texture._generateStencilBuffer = generateStencilBuffer;
  15407. texture._attachments = attachments;
  15408. this._internalTexturesCache.push(texture);
  15409. }
  15410. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15411. // Depth texture
  15412. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15413. gl.activeTexture(gl.TEXTURE0);
  15414. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15415. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15418. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15419. 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);
  15420. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15421. depthTexture._framebuffer = framebuffer;
  15422. depthTexture.baseWidth = width;
  15423. depthTexture.baseHeight = height;
  15424. depthTexture.width = width;
  15425. depthTexture.height = height;
  15426. depthTexture.isReady = true;
  15427. depthTexture.samples = 1;
  15428. depthTexture.generateMipMaps = generateMipMaps;
  15429. depthTexture.samplingMode = gl.NEAREST;
  15430. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15431. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15432. textures.push(depthTexture);
  15433. this._internalTexturesCache.push(depthTexture);
  15434. }
  15435. gl.drawBuffers(attachments);
  15436. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15437. this.bindUnboundFramebuffer(null);
  15438. this.resetTextureCache();
  15439. return textures;
  15440. };
  15441. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15442. if (samples === void 0) { samples = 1; }
  15443. var depthStencilBuffer = null;
  15444. var gl = this._gl;
  15445. // Create the depth/stencil buffer
  15446. if (generateStencilBuffer) {
  15447. depthStencilBuffer = gl.createRenderbuffer();
  15448. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15449. if (samples > 1) {
  15450. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15451. }
  15452. else {
  15453. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15454. }
  15455. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15456. }
  15457. else if (generateDepthBuffer) {
  15458. depthStencilBuffer = gl.createRenderbuffer();
  15459. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15460. if (samples > 1) {
  15461. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15462. }
  15463. else {
  15464. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15465. }
  15466. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15467. }
  15468. return depthStencilBuffer;
  15469. };
  15470. /**
  15471. * Updates the sample count of a render target texture
  15472. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15473. * @param texture defines the texture to update
  15474. * @param samples defines the sample count to set
  15475. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15476. */
  15477. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15478. if (this.webGLVersion < 2 || !texture) {
  15479. return 1;
  15480. }
  15481. if (texture.samples === samples) {
  15482. return samples;
  15483. }
  15484. var gl = this._gl;
  15485. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15486. // Dispose previous render buffers
  15487. if (texture._depthStencilBuffer) {
  15488. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15489. texture._depthStencilBuffer = null;
  15490. }
  15491. if (texture._MSAAFramebuffer) {
  15492. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15493. texture._MSAAFramebuffer = null;
  15494. }
  15495. if (texture._MSAARenderBuffer) {
  15496. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15497. texture._MSAARenderBuffer = null;
  15498. }
  15499. if (samples > 1) {
  15500. var framebuffer = gl.createFramebuffer();
  15501. if (!framebuffer) {
  15502. throw new Error("Unable to create multi sampled framebuffer");
  15503. }
  15504. texture._MSAAFramebuffer = framebuffer;
  15505. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15506. var colorRenderbuffer = gl.createRenderbuffer();
  15507. if (!colorRenderbuffer) {
  15508. throw new Error("Unable to create multi sampled framebuffer");
  15509. }
  15510. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15511. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15512. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15513. texture._MSAARenderBuffer = colorRenderbuffer;
  15514. }
  15515. else {
  15516. this.bindUnboundFramebuffer(texture._framebuffer);
  15517. }
  15518. texture.samples = samples;
  15519. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15520. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15521. this.bindUnboundFramebuffer(null);
  15522. return samples;
  15523. };
  15524. /**
  15525. * Update the sample count for a given multiple render target texture
  15526. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15527. * @param textures defines the textures to update
  15528. * @param samples defines the sample count to set
  15529. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15530. */
  15531. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15532. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15533. return 1;
  15534. }
  15535. if (textures[0].samples === samples) {
  15536. return samples;
  15537. }
  15538. var gl = this._gl;
  15539. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15540. // Dispose previous render buffers
  15541. if (textures[0]._depthStencilBuffer) {
  15542. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15543. textures[0]._depthStencilBuffer = null;
  15544. }
  15545. if (textures[0]._MSAAFramebuffer) {
  15546. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15547. textures[0]._MSAAFramebuffer = null;
  15548. }
  15549. for (var i = 0; i < textures.length; i++) {
  15550. if (textures[i]._MSAARenderBuffer) {
  15551. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15552. textures[i]._MSAARenderBuffer = null;
  15553. }
  15554. }
  15555. if (samples > 1) {
  15556. var framebuffer = gl.createFramebuffer();
  15557. if (!framebuffer) {
  15558. throw new Error("Unable to create multi sampled framebuffer");
  15559. }
  15560. this.bindUnboundFramebuffer(framebuffer);
  15561. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15562. var attachments = [];
  15563. for (var i = 0; i < textures.length; i++) {
  15564. var texture = textures[i];
  15565. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15566. var colorRenderbuffer = gl.createRenderbuffer();
  15567. if (!colorRenderbuffer) {
  15568. throw new Error("Unable to create multi sampled framebuffer");
  15569. }
  15570. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15571. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15572. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15573. texture._MSAAFramebuffer = framebuffer;
  15574. texture._MSAARenderBuffer = colorRenderbuffer;
  15575. texture.samples = samples;
  15576. texture._depthStencilBuffer = depthStencilBuffer;
  15577. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15578. attachments.push(attachment);
  15579. }
  15580. gl.drawBuffers(attachments);
  15581. }
  15582. else {
  15583. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15584. }
  15585. this.bindUnboundFramebuffer(null);
  15586. return samples;
  15587. };
  15588. /** @hidden */
  15589. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15590. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15591. };
  15592. /** @hidden */
  15593. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15594. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15595. };
  15596. /** @hidden */
  15597. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15598. var gl = this._gl;
  15599. var textureType = this._getWebGLTextureType(texture.type);
  15600. var format = this._getInternalFormat(texture.format);
  15601. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15602. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15603. this._bindTextureDirectly(bindTarget, texture, true);
  15604. this._unpackFlipY(texture.invertY);
  15605. var target = gl.TEXTURE_2D;
  15606. if (texture.isCube) {
  15607. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15608. }
  15609. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15610. this._bindTextureDirectly(bindTarget, null, true);
  15611. };
  15612. /**
  15613. * Creates a new render target cube texture
  15614. * @param size defines the size of the texture
  15615. * @param options defines the options used to create the texture
  15616. * @returns a new render target cube texture stored in an InternalTexture
  15617. */
  15618. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15619. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15620. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15621. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15622. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15623. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15624. }
  15625. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15626. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15627. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15628. }
  15629. var gl = this._gl;
  15630. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15631. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15632. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15633. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15634. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15635. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15636. }
  15637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15640. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15641. for (var face = 0; face < 6; face++) {
  15642. 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);
  15643. }
  15644. // Create the framebuffer
  15645. var framebuffer = gl.createFramebuffer();
  15646. this.bindUnboundFramebuffer(framebuffer);
  15647. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15648. // MipMaps
  15649. if (fullOptions.generateMipMaps) {
  15650. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15651. }
  15652. // Unbind
  15653. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15654. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15655. this.bindUnboundFramebuffer(null);
  15656. texture._framebuffer = framebuffer;
  15657. texture.width = size;
  15658. texture.height = size;
  15659. texture.isReady = true;
  15660. texture.isCube = true;
  15661. texture.samples = 1;
  15662. texture.generateMipMaps = fullOptions.generateMipMaps;
  15663. texture.samplingMode = fullOptions.samplingMode;
  15664. texture.type = fullOptions.type;
  15665. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15666. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15667. this._internalTexturesCache.push(texture);
  15668. return texture;
  15669. };
  15670. /**
  15671. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15672. * @param rootUrl defines the url where the file to load is located
  15673. * @param scene defines the current scene
  15674. * @param lodScale defines scale to apply to the mip map selection
  15675. * @param lodOffset defines offset to apply to the mip map selection
  15676. * @param onLoad defines an optional callback raised when the texture is loaded
  15677. * @param onError defines an optional callback raised if there is an issue to load the texture
  15678. * @param format defines the format of the data
  15679. * @param forcedExtension defines the extension to use to pick the right loader
  15680. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15681. * @returns the cube texture as an InternalTexture
  15682. */
  15683. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15684. var _this = this;
  15685. if (onLoad === void 0) { onLoad = null; }
  15686. if (onError === void 0) { onError = null; }
  15687. if (forcedExtension === void 0) { forcedExtension = null; }
  15688. if (createPolynomials === void 0) { createPolynomials = true; }
  15689. var callback = function (loadData) {
  15690. if (!loadData) {
  15691. if (onLoad) {
  15692. onLoad(null);
  15693. }
  15694. return;
  15695. }
  15696. var texture = loadData.texture;
  15697. if (!createPolynomials) {
  15698. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15699. }
  15700. else if (loadData.info.sphericalPolynomial) {
  15701. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15702. }
  15703. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15704. if (_this._caps.textureLOD) {
  15705. // Do not add extra process if texture lod is supported.
  15706. if (onLoad) {
  15707. onLoad(texture);
  15708. }
  15709. return;
  15710. }
  15711. var mipSlices = 3;
  15712. var gl = _this._gl;
  15713. var width = loadData.width;
  15714. if (!width) {
  15715. return;
  15716. }
  15717. var textures = [];
  15718. for (var i = 0; i < mipSlices; i++) {
  15719. //compute LOD from even spacing in smoothness (matching shader calculation)
  15720. var smoothness = i / (mipSlices - 1);
  15721. var roughness = 1 - smoothness;
  15722. var minLODIndex = lodOffset; // roughness = 0
  15723. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15724. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15725. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15726. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15727. glTextureFromLod.isCube = true;
  15728. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15732. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15733. if (loadData.isDDS) {
  15734. var info = loadData.info;
  15735. var data = loadData.data;
  15736. _this._unpackFlipY(info.isCompressed);
  15737. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15738. }
  15739. else {
  15740. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15741. }
  15742. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15743. // Wrap in a base texture for easy binding.
  15744. var lodTexture = new BABYLON.BaseTexture(scene);
  15745. lodTexture.isCube = true;
  15746. lodTexture._texture = glTextureFromLod;
  15747. glTextureFromLod.isReady = true;
  15748. textures.push(lodTexture);
  15749. }
  15750. texture._lodTextureHigh = textures[2];
  15751. texture._lodTextureMid = textures[1];
  15752. texture._lodTextureLow = textures[0];
  15753. if (onLoad) {
  15754. onLoad(texture);
  15755. }
  15756. };
  15757. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15758. };
  15759. /**
  15760. * Creates a cube texture
  15761. * @param rootUrl defines the url where the files to load is located
  15762. * @param scene defines the current scene
  15763. * @param files defines the list of files to load (1 per face)
  15764. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15765. * @param onLoad defines an optional callback raised when the texture is loaded
  15766. * @param onError defines an optional callback raised if there is an issue to load the texture
  15767. * @param format defines the format of the data
  15768. * @param forcedExtension defines the extension to use to pick the right loader
  15769. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15770. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15771. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15772. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15773. * @returns the cube texture as an InternalTexture
  15774. */
  15775. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15776. var _this = this;
  15777. if (onLoad === void 0) { onLoad = null; }
  15778. if (onError === void 0) { onError = null; }
  15779. if (forcedExtension === void 0) { forcedExtension = null; }
  15780. if (createPolynomials === void 0) { createPolynomials = false; }
  15781. if (lodScale === void 0) { lodScale = 0; }
  15782. if (lodOffset === void 0) { lodOffset = 0; }
  15783. if (fallback === void 0) { fallback = null; }
  15784. var gl = this._gl;
  15785. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15786. texture.isCube = true;
  15787. texture.url = rootUrl;
  15788. texture.generateMipMaps = !noMipmap;
  15789. texture._lodGenerationScale = lodScale;
  15790. texture._lodGenerationOffset = lodOffset;
  15791. if (!this._doNotHandleContextLost) {
  15792. texture._extension = forcedExtension;
  15793. texture._files = files;
  15794. }
  15795. var isKTX = false;
  15796. var isDDS = false;
  15797. var isEnv = false;
  15798. var lastDot = rootUrl.lastIndexOf('.');
  15799. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15800. if (this._textureFormatInUse && !fallback) {
  15801. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15802. isKTX = true;
  15803. }
  15804. else {
  15805. isDDS = (extension === ".dds");
  15806. isEnv = (extension === ".env");
  15807. }
  15808. var onerror = function (request, exception) {
  15809. if (isKTX) {
  15810. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15811. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15812. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15813. }
  15814. if (onError && request) {
  15815. onError(request.status + " " + request.statusText, exception);
  15816. }
  15817. };
  15818. if (isKTX) {
  15819. this._loadFile(rootUrl, function (data) {
  15820. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15821. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15822. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15823. _this._unpackFlipY(true);
  15824. ktx.uploadLevels(_this._gl, !noMipmap);
  15825. _this.setCubeMapTextureParams(gl, loadMipmap);
  15826. texture.width = ktx.pixelWidth;
  15827. texture.height = ktx.pixelHeight;
  15828. texture.isReady = true;
  15829. }, undefined, undefined, true, onerror);
  15830. }
  15831. else if (isEnv) {
  15832. this._loadFile(rootUrl, function (data) {
  15833. data = data;
  15834. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15835. if (info) {
  15836. texture.width = info.width;
  15837. texture.height = info.width;
  15838. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15839. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15840. texture.isReady = true;
  15841. if (onLoad) {
  15842. onLoad();
  15843. }
  15844. });
  15845. }
  15846. else if (onError) {
  15847. onError("Can not parse the environment file", null);
  15848. }
  15849. }, undefined, undefined, true, onerror);
  15850. }
  15851. else if (isDDS) {
  15852. if (files && files.length === 6) {
  15853. this._cascadeLoadFiles(scene, function (imgs) {
  15854. var info;
  15855. var loadMipmap = false;
  15856. var width = 0;
  15857. for (var index = 0; index < imgs.length; index++) {
  15858. var data = imgs[index];
  15859. info = BABYLON.DDSTools.GetDDSInfo(data);
  15860. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15861. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15862. _this._unpackFlipY(info.isCompressed);
  15863. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15864. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15865. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15866. }
  15867. texture.width = info.width;
  15868. texture.height = info.height;
  15869. texture.type = info.textureType;
  15870. width = info.width;
  15871. }
  15872. _this.setCubeMapTextureParams(gl, loadMipmap);
  15873. texture.isReady = true;
  15874. if (onLoad) {
  15875. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15876. }
  15877. }, files, onError);
  15878. }
  15879. else {
  15880. this._loadFile(rootUrl, function (data) {
  15881. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15882. if (createPolynomials) {
  15883. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15884. }
  15885. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15886. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15887. _this._unpackFlipY(info.isCompressed);
  15888. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15889. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15890. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15891. }
  15892. _this.setCubeMapTextureParams(gl, loadMipmap);
  15893. texture.width = info.width;
  15894. texture.height = info.height;
  15895. texture.isReady = true;
  15896. texture.type = info.textureType;
  15897. if (onLoad) {
  15898. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15899. }
  15900. }, undefined, undefined, true, onerror);
  15901. }
  15902. }
  15903. else {
  15904. if (!files) {
  15905. throw new Error("Cannot load cubemap because files were not defined");
  15906. }
  15907. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15908. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15909. var height = width;
  15910. _this._prepareWorkingCanvas();
  15911. if (!_this._workingCanvas || !_this._workingContext) {
  15912. return;
  15913. }
  15914. _this._workingCanvas.width = width;
  15915. _this._workingCanvas.height = height;
  15916. var faces = [
  15917. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15918. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15919. ];
  15920. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15921. _this._unpackFlipY(false);
  15922. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15923. for (var index = 0; index < faces.length; index++) {
  15924. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15925. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15926. }
  15927. if (!noMipmap) {
  15928. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15929. }
  15930. _this.setCubeMapTextureParams(gl, !noMipmap);
  15931. texture.width = width;
  15932. texture.height = height;
  15933. texture.isReady = true;
  15934. if (format) {
  15935. texture.format = format;
  15936. }
  15937. texture.onLoadedObservable.notifyObservers(texture);
  15938. texture.onLoadedObservable.clear();
  15939. if (onLoad) {
  15940. onLoad();
  15941. }
  15942. }, files, onError);
  15943. }
  15944. this._internalTexturesCache.push(texture);
  15945. return texture;
  15946. };
  15947. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15948. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15949. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15950. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15952. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15953. // this.resetTextureCache();
  15954. };
  15955. /**
  15956. * Update a raw cube texture
  15957. * @param texture defines the texture to udpdate
  15958. * @param data defines the data to store
  15959. * @param format defines the data format
  15960. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15961. * @param invertY defines if data must be stored with Y axis inverted
  15962. * @param compression defines the compression used (null by default)
  15963. * @param level defines which level of the texture to update
  15964. */
  15965. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15966. if (compression === void 0) { compression = null; }
  15967. if (level === void 0) { level = 0; }
  15968. texture._bufferViewArray = data;
  15969. texture.format = format;
  15970. texture.type = type;
  15971. texture.invertY = invertY;
  15972. texture._compression = compression;
  15973. var gl = this._gl;
  15974. var textureType = this._getWebGLTextureType(type);
  15975. var internalFormat = this._getInternalFormat(format);
  15976. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15977. var needConversion = false;
  15978. if (internalFormat === gl.RGB) {
  15979. internalFormat = gl.RGBA;
  15980. needConversion = true;
  15981. }
  15982. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15983. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15984. if (texture.width % 4 !== 0) {
  15985. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15986. }
  15987. // Data are known to be in +X +Y +Z -X -Y -Z
  15988. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15989. var faceData = data[faceIndex];
  15990. if (compression) {
  15991. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15992. }
  15993. else {
  15994. if (needConversion) {
  15995. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15996. }
  15997. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15998. }
  15999. }
  16000. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16001. if (isPot && texture.generateMipMaps && level === 0) {
  16002. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16003. }
  16004. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16005. // this.resetTextureCache();
  16006. texture.isReady = true;
  16007. };
  16008. /**
  16009. * Creates a new raw cube texture
  16010. * @param data defines the array of data to use to create each face
  16011. * @param size defines the size of the textures
  16012. * @param format defines the format of the data
  16013. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16014. * @param generateMipMaps defines if the engine should generate the mip levels
  16015. * @param invertY defines if data must be stored with Y axis inverted
  16016. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16017. * @param compression defines the compression used (null by default)
  16018. * @returns the cube texture as an InternalTexture
  16019. */
  16020. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16021. if (compression === void 0) { compression = null; }
  16022. var gl = this._gl;
  16023. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16024. texture.isCube = true;
  16025. texture.generateMipMaps = generateMipMaps;
  16026. texture.format = format;
  16027. texture.type = type;
  16028. if (!this._doNotHandleContextLost) {
  16029. texture._bufferViewArray = data;
  16030. }
  16031. var textureType = this._getWebGLTextureType(type);
  16032. var internalFormat = this._getInternalFormat(format);
  16033. if (internalFormat === gl.RGB) {
  16034. internalFormat = gl.RGBA;
  16035. }
  16036. var width = size;
  16037. var height = width;
  16038. texture.width = width;
  16039. texture.height = height;
  16040. // Double check on POT to generate Mips.
  16041. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16042. if (!isPot) {
  16043. generateMipMaps = false;
  16044. }
  16045. // Upload data if needed. The texture won't be ready until then.
  16046. if (data) {
  16047. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16048. }
  16049. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16050. // Filters
  16051. if (data && generateMipMaps) {
  16052. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16053. }
  16054. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16055. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16056. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16057. }
  16058. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16061. }
  16062. else {
  16063. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16066. }
  16067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16069. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16070. return texture;
  16071. };
  16072. /**
  16073. * Creates a new raw cube texture from a specified url
  16074. * @param url defines the url where the data is located
  16075. * @param scene defines the current scene
  16076. * @param size defines the size of the textures
  16077. * @param format defines the format of the data
  16078. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16079. * @param noMipmap defines if the engine should avoid generating the mip levels
  16080. * @param callback defines a callback used to extract texture data from loaded data
  16081. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16082. * @param onLoad defines a callback called when texture is loaded
  16083. * @param onError defines a callback called if there is an error
  16084. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16085. * @param invertY defines if data must be stored with Y axis inverted
  16086. * @returns the cube texture as an InternalTexture
  16087. */
  16088. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16089. var _this = this;
  16090. if (onLoad === void 0) { onLoad = null; }
  16091. if (onError === void 0) { onError = null; }
  16092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16093. if (invertY === void 0) { invertY = false; }
  16094. var gl = this._gl;
  16095. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16096. scene._addPendingData(texture);
  16097. texture.url = url;
  16098. this._internalTexturesCache.push(texture);
  16099. var onerror = function (request, exception) {
  16100. scene._removePendingData(texture);
  16101. if (onError && request) {
  16102. onError(request.status + " " + request.statusText, exception);
  16103. }
  16104. };
  16105. var internalCallback = function (data) {
  16106. var width = texture.width;
  16107. var faceDataArrays = callback(data);
  16108. if (!faceDataArrays) {
  16109. return;
  16110. }
  16111. if (mipmapGenerator) {
  16112. var textureType = _this._getWebGLTextureType(type);
  16113. var internalFormat = _this._getInternalFormat(format);
  16114. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16115. var needConversion = false;
  16116. if (internalFormat === gl.RGB) {
  16117. internalFormat = gl.RGBA;
  16118. needConversion = true;
  16119. }
  16120. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16121. _this._unpackFlipY(false);
  16122. var mipData = mipmapGenerator(faceDataArrays);
  16123. for (var level = 0; level < mipData.length; level++) {
  16124. var mipSize = width >> level;
  16125. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16126. var mipFaceData = mipData[level][faceIndex];
  16127. if (needConversion) {
  16128. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16129. }
  16130. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16131. }
  16132. }
  16133. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16134. }
  16135. else {
  16136. texture.generateMipMaps = !noMipmap;
  16137. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16138. }
  16139. texture.isReady = true;
  16140. // this.resetTextureCache();
  16141. scene._removePendingData(texture);
  16142. if (onLoad) {
  16143. onLoad();
  16144. }
  16145. };
  16146. this._loadFile(url, function (data) {
  16147. internalCallback(data);
  16148. }, undefined, scene.database, true, onerror);
  16149. return texture;
  16150. };
  16151. ;
  16152. /**
  16153. * Update a raw 3D texture
  16154. * @param texture defines the texture to update
  16155. * @param data defines the data to store
  16156. * @param format defines the data format
  16157. * @param invertY defines if data must be stored with Y axis inverted
  16158. * @param compression defines the used compression (can be null)
  16159. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16160. */
  16161. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16162. if (compression === void 0) { compression = null; }
  16163. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16164. var internalType = this._getWebGLTextureType(textureType);
  16165. var internalFormat = this._getInternalFormat(format);
  16166. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16167. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16168. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16169. if (!this._doNotHandleContextLost) {
  16170. texture._bufferView = data;
  16171. texture.format = format;
  16172. texture.invertY = invertY;
  16173. texture._compression = compression;
  16174. }
  16175. if (texture.width % 4 !== 0) {
  16176. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16177. }
  16178. if (compression && data) {
  16179. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16180. }
  16181. else {
  16182. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16183. }
  16184. if (texture.generateMipMaps) {
  16185. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16186. }
  16187. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16188. // this.resetTextureCache();
  16189. texture.isReady = true;
  16190. };
  16191. /**
  16192. * Creates a new raw 3D texture
  16193. * @param data defines the data used to create the texture
  16194. * @param width defines the width of the texture
  16195. * @param height defines the height of the texture
  16196. * @param depth defines the depth of the texture
  16197. * @param format defines the format of the texture
  16198. * @param generateMipMaps defines if the engine must generate mip levels
  16199. * @param invertY defines if data must be stored with Y axis inverted
  16200. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16201. * @param compression defines the compressed used (can be null)
  16202. * @param textureType defines the compressed used (can be null)
  16203. * @returns a new raw 3D texture (stored in an InternalTexture)
  16204. */
  16205. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16206. if (compression === void 0) { compression = null; }
  16207. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16208. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16209. texture.baseWidth = width;
  16210. texture.baseHeight = height;
  16211. texture.baseDepth = depth;
  16212. texture.width = width;
  16213. texture.height = height;
  16214. texture.depth = depth;
  16215. texture.format = format;
  16216. texture.type = textureType;
  16217. texture.generateMipMaps = generateMipMaps;
  16218. texture.samplingMode = samplingMode;
  16219. texture.is3D = true;
  16220. if (!this._doNotHandleContextLost) {
  16221. texture._bufferView = data;
  16222. }
  16223. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16224. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16225. // Filters
  16226. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16227. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16228. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16229. if (generateMipMaps) {
  16230. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16231. }
  16232. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16233. this._internalTexturesCache.push(texture);
  16234. return texture;
  16235. };
  16236. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16237. var gl = this._gl;
  16238. if (!gl) {
  16239. return;
  16240. }
  16241. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16243. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16244. if (!noMipmap && !isCompressed) {
  16245. gl.generateMipmap(gl.TEXTURE_2D);
  16246. }
  16247. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16248. // this.resetTextureCache();
  16249. if (scene) {
  16250. scene._removePendingData(texture);
  16251. }
  16252. texture.onLoadedObservable.notifyObservers(texture);
  16253. texture.onLoadedObservable.clear();
  16254. };
  16255. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16256. var _this = this;
  16257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16258. var maxTextureSize = this.getCaps().maxTextureSize;
  16259. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16260. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16261. var gl = this._gl;
  16262. if (!gl) {
  16263. return;
  16264. }
  16265. if (!texture._webGLTexture) {
  16266. // this.resetTextureCache();
  16267. if (scene) {
  16268. scene._removePendingData(texture);
  16269. }
  16270. return;
  16271. }
  16272. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16273. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16274. texture.baseWidth = width;
  16275. texture.baseHeight = height;
  16276. texture.width = potWidth;
  16277. texture.height = potHeight;
  16278. texture.isReady = true;
  16279. if (processFunction(potWidth, potHeight, function () {
  16280. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16281. })) {
  16282. // Returning as texture needs extra async steps
  16283. return;
  16284. }
  16285. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16286. };
  16287. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16288. // Create new RGBA data container.
  16289. var rgbaData;
  16290. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16291. rgbaData = new Float32Array(width * height * 4);
  16292. }
  16293. else {
  16294. rgbaData = new Uint32Array(width * height * 4);
  16295. }
  16296. // Convert each pixel.
  16297. for (var x = 0; x < width; x++) {
  16298. for (var y = 0; y < height; y++) {
  16299. var index = (y * width + x) * 3;
  16300. var newIndex = (y * width + x) * 4;
  16301. // Map Old Value to new value.
  16302. rgbaData[newIndex + 0] = rgbData[index + 0];
  16303. rgbaData[newIndex + 1] = rgbData[index + 1];
  16304. rgbaData[newIndex + 2] = rgbData[index + 2];
  16305. // Add fully opaque alpha channel.
  16306. rgbaData[newIndex + 3] = 1;
  16307. }
  16308. }
  16309. return rgbaData;
  16310. };
  16311. /** @hidden */
  16312. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16313. var gl = this._gl;
  16314. if (texture._framebuffer) {
  16315. gl.deleteFramebuffer(texture._framebuffer);
  16316. texture._framebuffer = null;
  16317. }
  16318. if (texture._depthStencilBuffer) {
  16319. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16320. texture._depthStencilBuffer = null;
  16321. }
  16322. if (texture._MSAAFramebuffer) {
  16323. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16324. texture._MSAAFramebuffer = null;
  16325. }
  16326. if (texture._MSAARenderBuffer) {
  16327. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16328. texture._MSAARenderBuffer = null;
  16329. }
  16330. };
  16331. /** @hidden */
  16332. Engine.prototype._releaseTexture = function (texture) {
  16333. var gl = this._gl;
  16334. this._releaseFramebufferObjects(texture);
  16335. gl.deleteTexture(texture._webGLTexture);
  16336. // Unbind channels
  16337. this.unbindAllTextures();
  16338. var index = this._internalTexturesCache.indexOf(texture);
  16339. if (index !== -1) {
  16340. this._internalTexturesCache.splice(index, 1);
  16341. }
  16342. // Integrated fixed lod samplers.
  16343. if (texture._lodTextureHigh) {
  16344. texture._lodTextureHigh.dispose();
  16345. }
  16346. if (texture._lodTextureMid) {
  16347. texture._lodTextureMid.dispose();
  16348. }
  16349. if (texture._lodTextureLow) {
  16350. texture._lodTextureLow.dispose();
  16351. }
  16352. // Set output texture of post process to null if the texture has been released/disposed
  16353. this.scenes.forEach(function (scene) {
  16354. scene.postProcesses.forEach(function (postProcess) {
  16355. if (postProcess._outputTexture == texture) {
  16356. postProcess._outputTexture = null;
  16357. }
  16358. });
  16359. scene.cameras.forEach(function (camera) {
  16360. camera._postProcesses.forEach(function (postProcess) {
  16361. if (postProcess) {
  16362. if (postProcess._outputTexture == texture) {
  16363. postProcess._outputTexture = null;
  16364. }
  16365. }
  16366. });
  16367. });
  16368. });
  16369. };
  16370. Engine.prototype.setProgram = function (program) {
  16371. if (this._currentProgram !== program) {
  16372. this._gl.useProgram(program);
  16373. this._currentProgram = program;
  16374. }
  16375. };
  16376. /**
  16377. * Binds an effect to the webGL context
  16378. * @param effect defines the effect to bind
  16379. */
  16380. Engine.prototype.bindSamplers = function (effect) {
  16381. this.setProgram(effect.getProgram());
  16382. var samplers = effect.getSamplers();
  16383. for (var index = 0; index < samplers.length; index++) {
  16384. var uniform = effect.getUniform(samplers[index]);
  16385. if (uniform) {
  16386. this._boundUniforms[index] = uniform;
  16387. }
  16388. }
  16389. this._currentEffect = null;
  16390. };
  16391. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16392. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16393. return;
  16394. }
  16395. // Remove
  16396. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16397. // Bind last to it
  16398. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16399. // Bind to dummy
  16400. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16401. };
  16402. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16403. if (!internalTexture) {
  16404. return -1;
  16405. }
  16406. internalTexture._initialSlot = channel;
  16407. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16408. if (channel !== internalTexture._designatedSlot) {
  16409. this._textureCollisions.addCount(1, false);
  16410. }
  16411. }
  16412. else {
  16413. if (channel !== internalTexture._designatedSlot) {
  16414. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16415. return internalTexture._designatedSlot;
  16416. }
  16417. else {
  16418. // No slot for this texture, let's pick a new one (if we find a free slot)
  16419. if (this._nextFreeTextureSlots.length) {
  16420. return this._nextFreeTextureSlots[0];
  16421. }
  16422. // We need to recycle the oldest bound texture, sorry.
  16423. this._textureCollisions.addCount(1, false);
  16424. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16425. }
  16426. }
  16427. }
  16428. return channel;
  16429. };
  16430. Engine.prototype._linkTrackers = function (previous, next) {
  16431. previous.next = next;
  16432. next.previous = previous;
  16433. };
  16434. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16435. var currentSlot = internalTexture._designatedSlot;
  16436. if (currentSlot === -1) {
  16437. return -1;
  16438. }
  16439. internalTexture._designatedSlot = -1;
  16440. if (this.disableTextureBindingOptimization) {
  16441. return -1;
  16442. }
  16443. // Remove from bound list
  16444. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16445. // Free the slot
  16446. this._boundTexturesCache[currentSlot] = null;
  16447. this._nextFreeTextureSlots.push(currentSlot);
  16448. return currentSlot;
  16449. };
  16450. Engine.prototype._activateCurrentTexture = function () {
  16451. if (this._currentTextureChannel !== this._activeChannel) {
  16452. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16453. this._currentTextureChannel = this._activeChannel;
  16454. }
  16455. };
  16456. /** @hidden */
  16457. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16458. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16459. if (force === void 0) { force = false; }
  16460. var wasPreviouslyBound = false;
  16461. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16462. this._activeChannel = texture._designatedSlot;
  16463. }
  16464. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16465. var isTextureForRendering = texture && texture._initialSlot > -1;
  16466. if (currentTextureBound !== texture || force) {
  16467. if (currentTextureBound) {
  16468. this._removeDesignatedSlot(currentTextureBound);
  16469. }
  16470. this._activateCurrentTexture();
  16471. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16472. this._boundTexturesCache[this._activeChannel] = texture;
  16473. if (texture) {
  16474. if (!this.disableTextureBindingOptimization) {
  16475. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16476. if (slotIndex > -1) {
  16477. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16478. }
  16479. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16480. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16481. }
  16482. texture._designatedSlot = this._activeChannel;
  16483. }
  16484. }
  16485. else if (forTextureDataUpdate) {
  16486. wasPreviouslyBound = true;
  16487. this._activateCurrentTexture();
  16488. }
  16489. if (isTextureForRendering && !forTextureDataUpdate) {
  16490. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16491. }
  16492. return wasPreviouslyBound;
  16493. };
  16494. /** @hidden */
  16495. Engine.prototype._bindTexture = function (channel, texture) {
  16496. if (channel < 0) {
  16497. return;
  16498. }
  16499. if (texture) {
  16500. channel = this._getCorrectTextureChannel(channel, texture);
  16501. }
  16502. this._activeChannel = channel;
  16503. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16504. };
  16505. /**
  16506. * Sets a texture to the webGL context from a postprocess
  16507. * @param channel defines the channel to use
  16508. * @param postProcess defines the source postprocess
  16509. */
  16510. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16511. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16512. };
  16513. /**
  16514. * Binds the output of the passed in post process to the texture channel specified
  16515. * @param channel The channel the texture should be bound to
  16516. * @param postProcess The post process which's output should be bound
  16517. */
  16518. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16519. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16520. };
  16521. /**
  16522. * Unbind all textures from the webGL context
  16523. */
  16524. Engine.prototype.unbindAllTextures = function () {
  16525. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16526. this._activeChannel = channel;
  16527. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16528. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16529. if (this.webGLVersion > 1) {
  16530. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16531. }
  16532. }
  16533. };
  16534. /**
  16535. * Sets a texture to the according uniform.
  16536. * @param channel The texture channel
  16537. * @param uniform The uniform to set
  16538. * @param texture The texture to apply
  16539. */
  16540. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16541. if (channel < 0) {
  16542. return;
  16543. }
  16544. if (uniform) {
  16545. this._boundUniforms[channel] = uniform;
  16546. }
  16547. this._setTexture(channel, texture);
  16548. };
  16549. /**
  16550. * Sets a depth stencil texture from a render target to the according uniform.
  16551. * @param channel The texture channel
  16552. * @param uniform The uniform to set
  16553. * @param texture The render target texture containing the depth stencil texture to apply
  16554. */
  16555. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16556. if (channel < 0) {
  16557. return;
  16558. }
  16559. if (uniform) {
  16560. this._boundUniforms[channel] = uniform;
  16561. }
  16562. if (!texture || !texture.depthStencilTexture) {
  16563. this._setTexture(channel, null);
  16564. }
  16565. else {
  16566. this._setTexture(channel, texture, false, true);
  16567. }
  16568. };
  16569. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16570. var uniform = this._boundUniforms[sourceSlot];
  16571. if (uniform._currentState === destination) {
  16572. return;
  16573. }
  16574. this._gl.uniform1i(uniform, destination);
  16575. uniform._currentState = destination;
  16576. };
  16577. Engine.prototype._getTextureWrapMode = function (mode) {
  16578. switch (mode) {
  16579. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16580. return this._gl.REPEAT;
  16581. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16582. return this._gl.CLAMP_TO_EDGE;
  16583. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16584. return this._gl.MIRRORED_REPEAT;
  16585. }
  16586. return this._gl.REPEAT;
  16587. };
  16588. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16589. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16590. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16591. // Not ready?
  16592. if (!texture) {
  16593. if (this._boundTexturesCache[channel] != null) {
  16594. this._activeChannel = channel;
  16595. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16596. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16597. if (this.webGLVersion > 1) {
  16598. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16599. }
  16600. }
  16601. return false;
  16602. }
  16603. // Video
  16604. if (texture.video) {
  16605. this._activeChannel = channel;
  16606. texture.update();
  16607. }
  16608. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16609. texture.delayLoad();
  16610. return false;
  16611. }
  16612. var internalTexture;
  16613. if (depthStencilTexture) {
  16614. internalTexture = texture.depthStencilTexture;
  16615. }
  16616. else if (texture.isReady()) {
  16617. internalTexture = texture.getInternalTexture();
  16618. }
  16619. else if (texture.isCube) {
  16620. internalTexture = this.emptyCubeTexture;
  16621. }
  16622. else if (texture.is3D) {
  16623. internalTexture = this.emptyTexture3D;
  16624. }
  16625. else {
  16626. internalTexture = this.emptyTexture;
  16627. }
  16628. if (!isPartOfTextureArray) {
  16629. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16630. }
  16631. var needToBind = true;
  16632. if (this._boundTexturesCache[channel] === internalTexture) {
  16633. this._moveBoundTextureOnTop(internalTexture);
  16634. if (!isPartOfTextureArray) {
  16635. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16636. }
  16637. needToBind = false;
  16638. }
  16639. this._activeChannel = channel;
  16640. if (internalTexture && internalTexture.is3D) {
  16641. if (needToBind) {
  16642. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16643. }
  16644. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16645. internalTexture._cachedWrapU = texture.wrapU;
  16646. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16647. }
  16648. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16649. internalTexture._cachedWrapV = texture.wrapV;
  16650. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16651. }
  16652. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16653. internalTexture._cachedWrapR = texture.wrapR;
  16654. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16655. }
  16656. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16657. }
  16658. else if (internalTexture && internalTexture.isCube) {
  16659. if (needToBind) {
  16660. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16661. }
  16662. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16663. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16664. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16665. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16666. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16667. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16668. }
  16669. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16670. }
  16671. else {
  16672. if (needToBind) {
  16673. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16674. }
  16675. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16676. internalTexture._cachedWrapU = texture.wrapU;
  16677. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16678. }
  16679. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16680. internalTexture._cachedWrapV = texture.wrapV;
  16681. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16682. }
  16683. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16684. }
  16685. return true;
  16686. };
  16687. /**
  16688. * Sets an array of texture to the webGL context
  16689. * @param channel defines the channel where the texture array must be set
  16690. * @param uniform defines the associated uniform location
  16691. * @param textures defines the array of textures to bind
  16692. */
  16693. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16694. if (channel < 0 || !uniform) {
  16695. return;
  16696. }
  16697. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16698. this._textureUnits = new Int32Array(textures.length);
  16699. }
  16700. for (var i = 0; i < textures.length; i++) {
  16701. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16702. }
  16703. this._gl.uniform1iv(uniform, this._textureUnits);
  16704. for (var index = 0; index < textures.length; index++) {
  16705. this._setTexture(this._textureUnits[index], textures[index], true);
  16706. }
  16707. };
  16708. /** @hidden */
  16709. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16710. var internalTexture = texture.getInternalTexture();
  16711. if (!internalTexture) {
  16712. return;
  16713. }
  16714. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16715. var value = texture.anisotropicFilteringLevel;
  16716. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16717. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16718. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16719. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16720. }
  16721. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16722. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16723. internalTexture._cachedAnisotropicFilteringLevel = value;
  16724. }
  16725. };
  16726. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16727. this._bindTextureDirectly(target, texture, true, true);
  16728. this._gl.texParameterf(target, parameter, value);
  16729. };
  16730. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16731. if (texture) {
  16732. this._bindTextureDirectly(target, texture, true, true);
  16733. }
  16734. this._gl.texParameteri(target, parameter, value);
  16735. };
  16736. /**
  16737. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16738. * @param x defines the x coordinate of the rectangle where pixels must be read
  16739. * @param y defines the y coordinate of the rectangle where pixels must be read
  16740. * @param width defines the width of the rectangle where pixels must be read
  16741. * @param height defines the height of the rectangle where pixels must be read
  16742. * @returns a Uint8Array containing RGBA colors
  16743. */
  16744. Engine.prototype.readPixels = function (x, y, width, height) {
  16745. var data = new Uint8Array(height * width * 4);
  16746. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16747. return data;
  16748. };
  16749. /**
  16750. * Add an externaly attached data from its key.
  16751. * This method call will fail and return false, if such key already exists.
  16752. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16753. * @param key the unique key that identifies the data
  16754. * @param data the data object to associate to the key for this Engine instance
  16755. * @return true if no such key were already present and the data was added successfully, false otherwise
  16756. */
  16757. Engine.prototype.addExternalData = function (key, data) {
  16758. if (!this._externalData) {
  16759. this._externalData = new BABYLON.StringDictionary();
  16760. }
  16761. return this._externalData.add(key, data);
  16762. };
  16763. /**
  16764. * Get an externaly attached data from its key
  16765. * @param key the unique key that identifies the data
  16766. * @return the associated data, if present (can be null), or undefined if not present
  16767. */
  16768. Engine.prototype.getExternalData = function (key) {
  16769. if (!this._externalData) {
  16770. this._externalData = new BABYLON.StringDictionary();
  16771. }
  16772. return this._externalData.get(key);
  16773. };
  16774. /**
  16775. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16776. * @param key the unique key that identifies the data
  16777. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16778. * @return the associated data, can be null if the factory returned null.
  16779. */
  16780. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16781. if (!this._externalData) {
  16782. this._externalData = new BABYLON.StringDictionary();
  16783. }
  16784. return this._externalData.getOrAddWithFactory(key, factory);
  16785. };
  16786. /**
  16787. * Remove an externaly attached data from the Engine instance
  16788. * @param key the unique key that identifies the data
  16789. * @return true if the data was successfully removed, false if it doesn't exist
  16790. */
  16791. Engine.prototype.removeExternalData = function (key) {
  16792. if (!this._externalData) {
  16793. this._externalData = new BABYLON.StringDictionary();
  16794. }
  16795. return this._externalData.remove(key);
  16796. };
  16797. /**
  16798. * Unbind all vertex attributes from the webGL context
  16799. */
  16800. Engine.prototype.unbindAllAttributes = function () {
  16801. if (this._mustWipeVertexAttributes) {
  16802. this._mustWipeVertexAttributes = false;
  16803. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16804. this._gl.disableVertexAttribArray(i);
  16805. this._vertexAttribArraysEnabled[i] = false;
  16806. this._currentBufferPointers[i].active = false;
  16807. }
  16808. return;
  16809. }
  16810. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16811. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16812. continue;
  16813. }
  16814. this._gl.disableVertexAttribArray(i);
  16815. this._vertexAttribArraysEnabled[i] = false;
  16816. this._currentBufferPointers[i].active = false;
  16817. }
  16818. };
  16819. /**
  16820. * 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
  16821. */
  16822. Engine.prototype.releaseEffects = function () {
  16823. for (var name in this._compiledEffects) {
  16824. this._deleteProgram(this._compiledEffects[name]._program);
  16825. }
  16826. this._compiledEffects = {};
  16827. };
  16828. /**
  16829. * Dispose and release all associated resources
  16830. */
  16831. Engine.prototype.dispose = function () {
  16832. this.hideLoadingUI();
  16833. this.stopRenderLoop();
  16834. // Release postProcesses
  16835. while (this.postProcesses.length) {
  16836. this.postProcesses[0].dispose();
  16837. }
  16838. // Empty texture
  16839. if (this._emptyTexture) {
  16840. this._releaseTexture(this._emptyTexture);
  16841. this._emptyTexture = null;
  16842. }
  16843. if (this._emptyCubeTexture) {
  16844. this._releaseTexture(this._emptyCubeTexture);
  16845. this._emptyCubeTexture = null;
  16846. }
  16847. // Rescale PP
  16848. if (this._rescalePostProcess) {
  16849. this._rescalePostProcess.dispose();
  16850. }
  16851. // Release scenes
  16852. while (this.scenes.length) {
  16853. this.scenes[0].dispose();
  16854. }
  16855. // Release audio engine
  16856. if (Engine.audioEngine) {
  16857. Engine.audioEngine.dispose();
  16858. }
  16859. // Release effects
  16860. this.releaseEffects();
  16861. // Unbind
  16862. this.unbindAllAttributes();
  16863. this._boundUniforms = [];
  16864. if (this._dummyFramebuffer) {
  16865. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16866. }
  16867. //WebVR
  16868. this.disableVR();
  16869. // Events
  16870. if (BABYLON.Tools.IsWindowObjectExist()) {
  16871. window.removeEventListener("blur", this._onBlur);
  16872. window.removeEventListener("focus", this._onFocus);
  16873. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16874. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16875. if (this._renderingCanvas) {
  16876. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16877. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16878. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16879. if (!this._doNotHandleContextLost) {
  16880. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16881. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16882. }
  16883. }
  16884. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16885. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16886. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16887. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16888. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16889. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16890. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16891. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16892. if (this._onVrDisplayConnect) {
  16893. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16894. if (this._onVrDisplayDisconnect) {
  16895. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16896. }
  16897. if (this._onVrDisplayPresentChange) {
  16898. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16899. }
  16900. this._onVrDisplayConnect = null;
  16901. this._onVrDisplayDisconnect = null;
  16902. }
  16903. }
  16904. // Remove from Instances
  16905. var index = Engine.Instances.indexOf(this);
  16906. if (index >= 0) {
  16907. Engine.Instances.splice(index, 1);
  16908. }
  16909. this._workingCanvas = null;
  16910. this._workingContext = null;
  16911. this._currentBufferPointers = [];
  16912. this._renderingCanvas = null;
  16913. this._currentProgram = null;
  16914. this._bindedRenderFunction = null;
  16915. this.onResizeObservable.clear();
  16916. this.onCanvasBlurObservable.clear();
  16917. this.onCanvasFocusObservable.clear();
  16918. this.onCanvasPointerOutObservable.clear();
  16919. this.onBeginFrameObservable.clear();
  16920. this.onEndFrameObservable.clear();
  16921. BABYLON.Effect.ResetCache();
  16922. // Abort active requests
  16923. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16924. var request = _a[_i];
  16925. request.abort();
  16926. }
  16927. };
  16928. // Loading screen
  16929. /**
  16930. * Display the loading screen
  16931. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16932. */
  16933. Engine.prototype.displayLoadingUI = function () {
  16934. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16935. return;
  16936. }
  16937. var loadingScreen = this.loadingScreen;
  16938. if (loadingScreen) {
  16939. loadingScreen.displayLoadingUI();
  16940. }
  16941. };
  16942. /**
  16943. * Hide the loading screen
  16944. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16945. */
  16946. Engine.prototype.hideLoadingUI = function () {
  16947. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16948. return;
  16949. }
  16950. var loadingScreen = this.loadingScreen;
  16951. if (loadingScreen) {
  16952. loadingScreen.hideLoadingUI();
  16953. }
  16954. };
  16955. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16956. /**
  16957. * Gets the current loading screen object
  16958. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16959. */
  16960. get: function () {
  16961. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16962. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16963. return this._loadingScreen;
  16964. },
  16965. /**
  16966. * Sets the current loading screen object
  16967. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16968. */
  16969. set: function (loadingScreen) {
  16970. this._loadingScreen = loadingScreen;
  16971. },
  16972. enumerable: true,
  16973. configurable: true
  16974. });
  16975. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16976. /**
  16977. * Sets the current loading screen text
  16978. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16979. */
  16980. set: function (text) {
  16981. this.loadingScreen.loadingUIText = text;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16987. /**
  16988. * Sets the current loading screen background color
  16989. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16990. */
  16991. set: function (color) {
  16992. this.loadingScreen.loadingUIBackgroundColor = color;
  16993. },
  16994. enumerable: true,
  16995. configurable: true
  16996. });
  16997. /**
  16998. * Attach a new callback raised when context lost event is fired
  16999. * @param callback defines the callback to call
  17000. */
  17001. Engine.prototype.attachContextLostEvent = function (callback) {
  17002. if (this._renderingCanvas) {
  17003. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17004. }
  17005. };
  17006. /**
  17007. * Attach a new callback raised when context restored event is fired
  17008. * @param callback defines the callback to call
  17009. */
  17010. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17011. if (this._renderingCanvas) {
  17012. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17013. }
  17014. };
  17015. /**
  17016. * Gets the source code of the vertex shader associated with a specific webGL program
  17017. * @param program defines the program to use
  17018. * @returns a string containing the source code of the vertex shader associated with the program
  17019. */
  17020. Engine.prototype.getVertexShaderSource = function (program) {
  17021. var shaders = this._gl.getAttachedShaders(program);
  17022. if (!shaders) {
  17023. return null;
  17024. }
  17025. return this._gl.getShaderSource(shaders[0]);
  17026. };
  17027. /**
  17028. * Gets the source code of the fragment shader associated with a specific webGL program
  17029. * @param program defines the program to use
  17030. * @returns a string containing the source code of the fragment shader associated with the program
  17031. */
  17032. Engine.prototype.getFragmentShaderSource = function (program) {
  17033. var shaders = this._gl.getAttachedShaders(program);
  17034. if (!shaders) {
  17035. return null;
  17036. }
  17037. return this._gl.getShaderSource(shaders[1]);
  17038. };
  17039. /**
  17040. * Get the current error code of the webGL context
  17041. * @returns the error code
  17042. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17043. */
  17044. Engine.prototype.getError = function () {
  17045. return this._gl.getError();
  17046. };
  17047. // FPS
  17048. /**
  17049. * Gets the current framerate
  17050. * @returns a number representing the framerate
  17051. */
  17052. Engine.prototype.getFps = function () {
  17053. return this._fps;
  17054. };
  17055. /**
  17056. * Gets the time spent between current and previous frame
  17057. * @returns a number representing the delta time in ms
  17058. */
  17059. Engine.prototype.getDeltaTime = function () {
  17060. return this._deltaTime;
  17061. };
  17062. Engine.prototype._measureFps = function () {
  17063. this._performanceMonitor.sampleFrame();
  17064. this._fps = this._performanceMonitor.averageFPS;
  17065. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17066. };
  17067. /** @hidden */
  17068. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17069. if (faceIndex === void 0) { faceIndex = -1; }
  17070. if (level === void 0) { level = 0; }
  17071. var gl = this._gl;
  17072. if (!this._dummyFramebuffer) {
  17073. var dummy = gl.createFramebuffer();
  17074. if (!dummy) {
  17075. throw new Error("Unable to create dummy framebuffer");
  17076. }
  17077. this._dummyFramebuffer = dummy;
  17078. }
  17079. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17080. if (faceIndex > -1) {
  17081. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17082. }
  17083. else {
  17084. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17085. }
  17086. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17087. var buffer;
  17088. switch (readType) {
  17089. case gl.UNSIGNED_BYTE:
  17090. buffer = new Uint8Array(4 * width * height);
  17091. readType = gl.UNSIGNED_BYTE;
  17092. break;
  17093. default:
  17094. buffer = new Float32Array(4 * width * height);
  17095. readType = gl.FLOAT;
  17096. break;
  17097. }
  17098. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17099. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17100. return buffer;
  17101. };
  17102. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17103. if (this._webGLVersion > 1) {
  17104. return this._caps.colorBufferFloat;
  17105. }
  17106. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17107. };
  17108. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17109. if (this._webGLVersion > 1) {
  17110. return this._caps.colorBufferFloat;
  17111. }
  17112. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17113. };
  17114. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17115. Engine.prototype._canRenderToFramebuffer = function (type) {
  17116. var gl = this._gl;
  17117. //clear existing errors
  17118. while (gl.getError() !== gl.NO_ERROR) { }
  17119. var successful = true;
  17120. var texture = gl.createTexture();
  17121. gl.bindTexture(gl.TEXTURE_2D, texture);
  17122. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17125. var fb = gl.createFramebuffer();
  17126. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17127. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17128. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17129. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17130. successful = successful && (gl.getError() === gl.NO_ERROR);
  17131. //try render by clearing frame buffer's color buffer
  17132. if (successful) {
  17133. gl.clear(gl.COLOR_BUFFER_BIT);
  17134. successful = successful && (gl.getError() === gl.NO_ERROR);
  17135. }
  17136. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17137. if (successful) {
  17138. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17139. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17140. var readFormat = gl.RGBA;
  17141. var readType = gl.UNSIGNED_BYTE;
  17142. var buffer = new Uint8Array(4);
  17143. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17144. successful = successful && (gl.getError() === gl.NO_ERROR);
  17145. }
  17146. //clean up
  17147. gl.deleteTexture(texture);
  17148. gl.deleteFramebuffer(fb);
  17149. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17150. //clear accumulated errors
  17151. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17152. return successful;
  17153. };
  17154. /** @hidden */
  17155. Engine.prototype._getWebGLTextureType = function (type) {
  17156. if (type === Engine.TEXTURETYPE_FLOAT) {
  17157. return this._gl.FLOAT;
  17158. }
  17159. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17160. // Add Half Float Constant.
  17161. return this._gl.HALF_FLOAT_OES;
  17162. }
  17163. return this._gl.UNSIGNED_BYTE;
  17164. };
  17165. ;
  17166. Engine.prototype._getInternalFormat = function (format) {
  17167. var internalFormat = this._gl.RGBA;
  17168. switch (format) {
  17169. case Engine.TEXTUREFORMAT_ALPHA:
  17170. internalFormat = this._gl.ALPHA;
  17171. break;
  17172. case Engine.TEXTUREFORMAT_LUMINANCE:
  17173. internalFormat = this._gl.LUMINANCE;
  17174. break;
  17175. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17176. internalFormat = this._gl.LUMINANCE_ALPHA;
  17177. break;
  17178. case Engine.TEXTUREFORMAT_RGB:
  17179. internalFormat = this._gl.RGB;
  17180. break;
  17181. case Engine.TEXTUREFORMAT_RGBA:
  17182. internalFormat = this._gl.RGBA;
  17183. break;
  17184. case Engine.TEXTUREFORMAT_R:
  17185. internalFormat = this._gl.RED;
  17186. break;
  17187. case Engine.TEXTUREFORMAT_RG:
  17188. internalFormat = this._gl.RG;
  17189. break;
  17190. }
  17191. return internalFormat;
  17192. };
  17193. /** @hidden */
  17194. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17195. if (this._webGLVersion === 1) {
  17196. if (format !== undefined) {
  17197. switch (format) {
  17198. case Engine.TEXTUREFORMAT_LUMINANCE:
  17199. return this._gl.LUMINANCE;
  17200. case Engine.TEXTUREFORMAT_ALPHA:
  17201. return this._gl.ALPHA;
  17202. }
  17203. }
  17204. return this._gl.RGBA;
  17205. }
  17206. if (type === Engine.TEXTURETYPE_FLOAT) {
  17207. if (format !== undefined) {
  17208. switch (format) {
  17209. case Engine.TEXTUREFORMAT_R:
  17210. return this._gl.R32F;
  17211. case Engine.TEXTUREFORMAT_RG:
  17212. return this._gl.RG32F;
  17213. case Engine.TEXTUREFORMAT_RGB:
  17214. return this._gl.RGB32F;
  17215. }
  17216. }
  17217. return this._gl.RGBA32F;
  17218. }
  17219. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17220. if (format) {
  17221. switch (format) {
  17222. case Engine.TEXTUREFORMAT_R:
  17223. return this._gl.R16F;
  17224. case Engine.TEXTUREFORMAT_RG:
  17225. return this._gl.RG16F;
  17226. case Engine.TEXTUREFORMAT_RGB:
  17227. return this._gl.RGB16F;
  17228. }
  17229. }
  17230. return this._gl.RGBA16F;
  17231. }
  17232. if (format !== undefined) {
  17233. switch (format) {
  17234. case Engine.TEXTUREFORMAT_LUMINANCE:
  17235. return this._gl.LUMINANCE;
  17236. case Engine.TEXTUREFORMAT_RGB:
  17237. return this._gl.RGB;
  17238. case Engine.TEXTUREFORMAT_R:
  17239. return this._gl.R8;
  17240. case Engine.TEXTUREFORMAT_RG:
  17241. return this._gl.RG8;
  17242. case Engine.TEXTUREFORMAT_ALPHA:
  17243. return this._gl.ALPHA;
  17244. }
  17245. }
  17246. return this._gl.RGBA;
  17247. };
  17248. ;
  17249. /** @hidden */
  17250. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17251. if (type === Engine.TEXTURETYPE_FLOAT) {
  17252. return this._gl.RGBA32F;
  17253. }
  17254. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17255. return this._gl.RGBA16F;
  17256. }
  17257. return this._gl.RGBA8;
  17258. };
  17259. ;
  17260. /**
  17261. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17262. * @return the new query
  17263. */
  17264. Engine.prototype.createQuery = function () {
  17265. return this._gl.createQuery();
  17266. };
  17267. /**
  17268. * Delete and release a webGL query
  17269. * @param query defines the query to delete
  17270. * @return the current engine
  17271. */
  17272. Engine.prototype.deleteQuery = function (query) {
  17273. this._gl.deleteQuery(query);
  17274. return this;
  17275. };
  17276. /**
  17277. * Check if a given query has resolved and got its value
  17278. * @param query defines the query to check
  17279. * @returns true if the query got its value
  17280. */
  17281. Engine.prototype.isQueryResultAvailable = function (query) {
  17282. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17283. };
  17284. /**
  17285. * Gets the value of a given query
  17286. * @param query defines the query to check
  17287. * @returns the value of the query
  17288. */
  17289. Engine.prototype.getQueryResult = function (query) {
  17290. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17291. };
  17292. /**
  17293. * Initiates an occlusion query
  17294. * @param algorithmType defines the algorithm to use
  17295. * @param query defines the query to use
  17296. * @returns the current engine
  17297. * @see http://doc.babylonjs.com/features/occlusionquery
  17298. */
  17299. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17300. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17301. this._gl.beginQuery(glAlgorithm, query);
  17302. return this;
  17303. };
  17304. /**
  17305. * Ends an occlusion query
  17306. * @see http://doc.babylonjs.com/features/occlusionquery
  17307. * @param algorithmType defines the algorithm to use
  17308. * @returns the current engine
  17309. */
  17310. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17311. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17312. this._gl.endQuery(glAlgorithm);
  17313. return this;
  17314. };
  17315. /* Time queries */
  17316. Engine.prototype._createTimeQuery = function () {
  17317. var timerQuery = this._caps.timerQuery;
  17318. if (timerQuery.createQueryEXT) {
  17319. return timerQuery.createQueryEXT();
  17320. }
  17321. return this.createQuery();
  17322. };
  17323. Engine.prototype._deleteTimeQuery = function (query) {
  17324. var timerQuery = this._caps.timerQuery;
  17325. if (timerQuery.deleteQueryEXT) {
  17326. timerQuery.deleteQueryEXT(query);
  17327. return;
  17328. }
  17329. this.deleteQuery(query);
  17330. };
  17331. Engine.prototype._getTimeQueryResult = function (query) {
  17332. var timerQuery = this._caps.timerQuery;
  17333. if (timerQuery.getQueryObjectEXT) {
  17334. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17335. }
  17336. return this.getQueryResult(query);
  17337. };
  17338. Engine.prototype._getTimeQueryAvailability = function (query) {
  17339. var timerQuery = this._caps.timerQuery;
  17340. if (timerQuery.getQueryObjectEXT) {
  17341. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17342. }
  17343. return this.isQueryResultAvailable(query);
  17344. };
  17345. /**
  17346. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17347. * Please note that only one query can be issued at a time
  17348. * @returns a time token used to track the time span
  17349. */
  17350. Engine.prototype.startTimeQuery = function () {
  17351. var timerQuery = this._caps.timerQuery;
  17352. if (!timerQuery) {
  17353. return null;
  17354. }
  17355. var token = new BABYLON._TimeToken();
  17356. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17357. if (this._caps.canUseTimestampForTimerQuery) {
  17358. token._startTimeQuery = this._createTimeQuery();
  17359. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17360. }
  17361. else {
  17362. if (this._currentNonTimestampToken) {
  17363. return this._currentNonTimestampToken;
  17364. }
  17365. token._timeElapsedQuery = this._createTimeQuery();
  17366. if (timerQuery.beginQueryEXT) {
  17367. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17368. }
  17369. else {
  17370. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17371. }
  17372. this._currentNonTimestampToken = token;
  17373. }
  17374. return token;
  17375. };
  17376. /**
  17377. * Ends a time query
  17378. * @param token defines the token used to measure the time span
  17379. * @returns the time spent (in ns)
  17380. */
  17381. Engine.prototype.endTimeQuery = function (token) {
  17382. var timerQuery = this._caps.timerQuery;
  17383. if (!timerQuery || !token) {
  17384. return -1;
  17385. }
  17386. if (this._caps.canUseTimestampForTimerQuery) {
  17387. if (!token._startTimeQuery) {
  17388. return -1;
  17389. }
  17390. if (!token._endTimeQuery) {
  17391. token._endTimeQuery = this._createTimeQuery();
  17392. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17393. }
  17394. }
  17395. else if (!token._timeElapsedQueryEnded) {
  17396. if (!token._timeElapsedQuery) {
  17397. return -1;
  17398. }
  17399. if (timerQuery.endQueryEXT) {
  17400. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17401. }
  17402. else {
  17403. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17404. }
  17405. token._timeElapsedQueryEnded = true;
  17406. }
  17407. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17408. var available = false;
  17409. if (token._endTimeQuery) {
  17410. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17411. }
  17412. else if (token._timeElapsedQuery) {
  17413. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17414. }
  17415. if (available && !disjoint) {
  17416. var result = 0;
  17417. if (this._caps.canUseTimestampForTimerQuery) {
  17418. if (!token._startTimeQuery || !token._endTimeQuery) {
  17419. return -1;
  17420. }
  17421. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17422. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17423. result = timeEnd - timeStart;
  17424. this._deleteTimeQuery(token._startTimeQuery);
  17425. this._deleteTimeQuery(token._endTimeQuery);
  17426. token._startTimeQuery = null;
  17427. token._endTimeQuery = null;
  17428. }
  17429. else {
  17430. if (!token._timeElapsedQuery) {
  17431. return -1;
  17432. }
  17433. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17434. this._deleteTimeQuery(token._timeElapsedQuery);
  17435. token._timeElapsedQuery = null;
  17436. token._timeElapsedQueryEnded = false;
  17437. this._currentNonTimestampToken = null;
  17438. }
  17439. return result;
  17440. }
  17441. return -1;
  17442. };
  17443. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17444. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17445. };
  17446. // Transform feedback
  17447. /**
  17448. * Creates a webGL transform feedback object
  17449. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17450. * @returns the webGL transform feedback object
  17451. */
  17452. Engine.prototype.createTransformFeedback = function () {
  17453. return this._gl.createTransformFeedback();
  17454. };
  17455. /**
  17456. * Delete a webGL transform feedback object
  17457. * @param value defines the webGL transform feedback object to delete
  17458. */
  17459. Engine.prototype.deleteTransformFeedback = function (value) {
  17460. this._gl.deleteTransformFeedback(value);
  17461. };
  17462. /**
  17463. * Bind a webGL transform feedback object to the webgl context
  17464. * @param value defines the webGL transform feedback object to bind
  17465. */
  17466. Engine.prototype.bindTransformFeedback = function (value) {
  17467. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17468. };
  17469. /**
  17470. * Begins a transform feedback operation
  17471. * @param usePoints defines if points or triangles must be used
  17472. */
  17473. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17474. if (usePoints === void 0) { usePoints = true; }
  17475. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17476. };
  17477. /**
  17478. * Ends a transform feedback operation
  17479. */
  17480. Engine.prototype.endTransformFeedback = function () {
  17481. this._gl.endTransformFeedback();
  17482. };
  17483. /**
  17484. * Specify the varyings to use with transform feedback
  17485. * @param program defines the associated webGL program
  17486. * @param value defines the list of strings representing the varying names
  17487. */
  17488. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17489. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17490. };
  17491. /**
  17492. * Bind a webGL buffer for a transform feedback operation
  17493. * @param value defines the webGL buffer to bind
  17494. */
  17495. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17496. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17497. };
  17498. /** @hidden */
  17499. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17500. var _this = this;
  17501. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17502. this._activeRequests.push(request);
  17503. request.onCompleteObservable.add(function (request) {
  17504. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17505. });
  17506. return request;
  17507. };
  17508. /** @hidden */
  17509. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17510. var _this = this;
  17511. return new Promise(function (resolve, reject) {
  17512. _this._loadFile(url, function (data) {
  17513. resolve(data);
  17514. }, undefined, database, useArrayBuffer, function (request, exception) {
  17515. reject(exception);
  17516. });
  17517. });
  17518. };
  17519. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17520. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17521. var onload = function (data) {
  17522. loadedFiles[index] = data;
  17523. loadedFiles._internalCount++;
  17524. if (loadedFiles._internalCount === 6) {
  17525. onfinish(loadedFiles);
  17526. }
  17527. };
  17528. var onerror = function (request, exception) {
  17529. if (onErrorCallBack && request) {
  17530. onErrorCallBack(request.status + " " + request.statusText, exception);
  17531. }
  17532. };
  17533. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17534. };
  17535. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17536. if (onError === void 0) { onError = null; }
  17537. var loadedFiles = [];
  17538. loadedFiles._internalCount = 0;
  17539. for (var index = 0; index < 6; index++) {
  17540. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17541. }
  17542. };
  17543. // Statics
  17544. /**
  17545. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17546. * @returns true if the engine can be created
  17547. * @ignorenaming
  17548. */
  17549. Engine.isSupported = function () {
  17550. try {
  17551. var tempcanvas = document.createElement("canvas");
  17552. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17553. return gl != null && !!window.WebGLRenderingContext;
  17554. }
  17555. catch (e) {
  17556. return false;
  17557. }
  17558. };
  17559. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17560. Engine.ExceptionList = [
  17561. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17562. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17563. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17564. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17565. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17566. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17567. ];
  17568. /** Gets the list of created engines */
  17569. Engine.Instances = new Array();
  17570. // Const statics
  17571. Engine._ALPHA_DISABLE = 0;
  17572. Engine._ALPHA_ADD = 1;
  17573. Engine._ALPHA_COMBINE = 2;
  17574. Engine._ALPHA_SUBTRACT = 3;
  17575. Engine._ALPHA_MULTIPLY = 4;
  17576. Engine._ALPHA_MAXIMIZED = 5;
  17577. Engine._ALPHA_ONEONE = 6;
  17578. Engine._ALPHA_PREMULTIPLIED = 7;
  17579. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17580. Engine._ALPHA_INTERPOLATE = 9;
  17581. Engine._ALPHA_SCREENMODE = 10;
  17582. Engine._DELAYLOADSTATE_NONE = 0;
  17583. Engine._DELAYLOADSTATE_LOADED = 1;
  17584. Engine._DELAYLOADSTATE_LOADING = 2;
  17585. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17586. Engine._TEXTUREFORMAT_ALPHA = 0;
  17587. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17588. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17589. Engine._TEXTUREFORMAT_RGB = 4;
  17590. Engine._TEXTUREFORMAT_RGBA = 5;
  17591. Engine._TEXTUREFORMAT_R = 6;
  17592. Engine._TEXTUREFORMAT_RG = 7;
  17593. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17594. Engine._TEXTURETYPE_FLOAT = 1;
  17595. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17596. // Depht or Stencil test Constants.
  17597. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17598. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17599. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17600. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17601. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17602. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17603. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17604. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17605. // Stencil Actions Constants.
  17606. Engine._KEEP = 0x1E00;
  17607. Engine._REPLACE = 0x1E01;
  17608. Engine._INCR = 0x1E02;
  17609. Engine._DECR = 0x1E03;
  17610. Engine._INVERT = 0x150A;
  17611. Engine._INCR_WRAP = 0x8507;
  17612. Engine._DECR_WRAP = 0x8508;
  17613. // Texture rescaling mode
  17614. Engine._SCALEMODE_FLOOR = 1;
  17615. Engine._SCALEMODE_NEAREST = 2;
  17616. Engine._SCALEMODE_CEILING = 3;
  17617. // Updatable statics so stick with vars here
  17618. /**
  17619. * Gets or sets the epsilon value used by collision engine
  17620. */
  17621. Engine.CollisionsEpsilon = 0.001;
  17622. /**
  17623. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17624. */
  17625. Engine.CodeRepository = "src/";
  17626. /**
  17627. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17628. */
  17629. Engine.ShadersRepository = "src/Shaders/";
  17630. return Engine;
  17631. }());
  17632. BABYLON.Engine = Engine;
  17633. })(BABYLON || (BABYLON = {}));
  17634. //# sourceMappingURL=babylon.engine.js.map
  17635. var BABYLON;
  17636. (function (BABYLON) {
  17637. /**
  17638. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17639. */
  17640. var Node = /** @class */ (function () {
  17641. /**
  17642. * Creates a new Node
  17643. * @param {string} name - the name and id to be given to this node
  17644. * @param {BABYLON.Scene} the scene this node will be added to
  17645. */
  17646. function Node(name, scene) {
  17647. if (scene === void 0) { scene = null; }
  17648. /**
  17649. * Gets or sets a string used to store user defined state for the node
  17650. */
  17651. this.state = "";
  17652. /**
  17653. * Gets or sets an object used to store user defined information for the node
  17654. */
  17655. this.metadata = null;
  17656. /**
  17657. * Gets or sets a boolean used to define if the node must be serialized
  17658. */
  17659. this.doNotSerialize = false;
  17660. /** @hidden */
  17661. this._isDisposed = false;
  17662. /**
  17663. * Gets a list of Animations associated with the node
  17664. */
  17665. this.animations = new Array();
  17666. this._ranges = {};
  17667. this._isEnabled = true;
  17668. this._isReady = true;
  17669. /** @hidden */
  17670. this._currentRenderId = -1;
  17671. this._parentRenderId = -1;
  17672. this._childRenderId = -1;
  17673. this._animationPropertiesOverride = null;
  17674. /**
  17675. * An event triggered when the mesh is disposed
  17676. */
  17677. this.onDisposeObservable = new BABYLON.Observable();
  17678. // Behaviors
  17679. this._behaviors = new Array();
  17680. this.name = name;
  17681. this.id = name;
  17682. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17683. this.uniqueId = this._scene.getUniqueId();
  17684. this._initCache();
  17685. }
  17686. /**
  17687. * Gets a boolean indicating if the node has been disposed
  17688. * @returns true if the node was disposed
  17689. */
  17690. Node.prototype.isDisposed = function () {
  17691. return this._isDisposed;
  17692. };
  17693. Object.defineProperty(Node.prototype, "parent", {
  17694. get: function () {
  17695. return this._parentNode;
  17696. },
  17697. /**
  17698. * Gets or sets the parent of the node
  17699. */
  17700. set: function (parent) {
  17701. if (this._parentNode === parent) {
  17702. return;
  17703. }
  17704. // Remove self from list of children of parent
  17705. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17706. var index = this._parentNode._children.indexOf(this);
  17707. if (index !== -1) {
  17708. this._parentNode._children.splice(index, 1);
  17709. }
  17710. }
  17711. // Store new parent
  17712. this._parentNode = parent;
  17713. // Add as child to new parent
  17714. if (this._parentNode) {
  17715. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17716. this._parentNode._children = new Array();
  17717. }
  17718. this._parentNode._children.push(this);
  17719. }
  17720. },
  17721. enumerable: true,
  17722. configurable: true
  17723. });
  17724. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17725. /**
  17726. * Gets or sets the animation properties override
  17727. */
  17728. get: function () {
  17729. if (!this._animationPropertiesOverride) {
  17730. return this._scene.animationPropertiesOverride;
  17731. }
  17732. return this._animationPropertiesOverride;
  17733. },
  17734. set: function (value) {
  17735. this._animationPropertiesOverride = value;
  17736. },
  17737. enumerable: true,
  17738. configurable: true
  17739. });
  17740. /**
  17741. * Gets a string idenfifying the name of the class
  17742. * @returns "Node" string
  17743. */
  17744. Node.prototype.getClassName = function () {
  17745. return "Node";
  17746. };
  17747. Object.defineProperty(Node.prototype, "onDispose", {
  17748. /**
  17749. * Sets a callback that will be raised when the node will be disposed
  17750. */
  17751. set: function (callback) {
  17752. if (this._onDisposeObserver) {
  17753. this.onDisposeObservable.remove(this._onDisposeObserver);
  17754. }
  17755. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17756. },
  17757. enumerable: true,
  17758. configurable: true
  17759. });
  17760. /**
  17761. * Gets the scene of the node
  17762. * @returns a {BABYLON.Scene}
  17763. */
  17764. Node.prototype.getScene = function () {
  17765. return this._scene;
  17766. };
  17767. /**
  17768. * Gets the engine of the node
  17769. * @returns a {BABYLON.Engine}
  17770. */
  17771. Node.prototype.getEngine = function () {
  17772. return this._scene.getEngine();
  17773. };
  17774. /**
  17775. * Attach a behavior to the node
  17776. * @see http://doc.babylonjs.com/features/behaviour
  17777. * @param behavior defines the behavior to attach
  17778. * @returns the current Node
  17779. */
  17780. Node.prototype.addBehavior = function (behavior) {
  17781. var _this = this;
  17782. var index = this._behaviors.indexOf(behavior);
  17783. if (index !== -1) {
  17784. return this;
  17785. }
  17786. behavior.init();
  17787. if (this._scene.isLoading) {
  17788. // We defer the attach when the scene will be loaded
  17789. this._scene.onDataLoadedObservable.addOnce(function () {
  17790. behavior.attach(_this);
  17791. });
  17792. }
  17793. else {
  17794. behavior.attach(this);
  17795. }
  17796. this._behaviors.push(behavior);
  17797. return this;
  17798. };
  17799. /**
  17800. * Remove an attached behavior
  17801. * @see http://doc.babylonjs.com/features/behaviour
  17802. * @param behavior defines the behavior to attach
  17803. * @returns the current Node
  17804. */
  17805. Node.prototype.removeBehavior = function (behavior) {
  17806. var index = this._behaviors.indexOf(behavior);
  17807. if (index === -1) {
  17808. return this;
  17809. }
  17810. this._behaviors[index].detach();
  17811. this._behaviors.splice(index, 1);
  17812. return this;
  17813. };
  17814. Object.defineProperty(Node.prototype, "behaviors", {
  17815. /**
  17816. * Gets the list of attached behaviors
  17817. * @see http://doc.babylonjs.com/features/behaviour
  17818. */
  17819. get: function () {
  17820. return this._behaviors;
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. /**
  17826. * Gets an attached behavior by name
  17827. * @param name defines the name of the behavior to look for
  17828. * @see http://doc.babylonjs.com/features/behaviour
  17829. * @returns null if behavior was not found else the requested behavior
  17830. */
  17831. Node.prototype.getBehaviorByName = function (name) {
  17832. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17833. var behavior = _a[_i];
  17834. if (behavior.name === name) {
  17835. return behavior;
  17836. }
  17837. }
  17838. return null;
  17839. };
  17840. /**
  17841. * Returns the world matrix of the node
  17842. * @returns a matrix containing the node's world matrix
  17843. */
  17844. Node.prototype.getWorldMatrix = function () {
  17845. return BABYLON.Matrix.Identity();
  17846. };
  17847. /** @hidden */
  17848. Node.prototype._getWorldMatrixDeterminant = function () {
  17849. return 1;
  17850. };
  17851. // override it in derived class if you add new variables to the cache
  17852. // and call the parent class method
  17853. /** @hidden */
  17854. Node.prototype._initCache = function () {
  17855. this._cache = {};
  17856. this._cache.parent = undefined;
  17857. };
  17858. /** @hidden */
  17859. Node.prototype.updateCache = function (force) {
  17860. if (!force && this.isSynchronized())
  17861. return;
  17862. this._cache.parent = this.parent;
  17863. this._updateCache();
  17864. };
  17865. // override it in derived class if you add new variables to the cache
  17866. // and call the parent class method if !ignoreParentClass
  17867. /** @hidden */
  17868. Node.prototype._updateCache = function (ignoreParentClass) {
  17869. };
  17870. // override it in derived class if you add new variables to the cache
  17871. /** @hidden */
  17872. Node.prototype._isSynchronized = function () {
  17873. return true;
  17874. };
  17875. /** @hidden */
  17876. Node.prototype._markSyncedWithParent = function () {
  17877. if (this.parent) {
  17878. this._parentRenderId = this.parent._childRenderId;
  17879. }
  17880. };
  17881. /** @hidden */
  17882. Node.prototype.isSynchronizedWithParent = function () {
  17883. if (!this.parent) {
  17884. return true;
  17885. }
  17886. if (this._parentRenderId !== this.parent._childRenderId) {
  17887. return false;
  17888. }
  17889. return this.parent.isSynchronized();
  17890. };
  17891. /** @hidden */
  17892. Node.prototype.isSynchronized = function (updateCache) {
  17893. var check = this.hasNewParent();
  17894. check = check || !this.isSynchronizedWithParent();
  17895. check = check || !this._isSynchronized();
  17896. if (updateCache)
  17897. this.updateCache(true);
  17898. return !check;
  17899. };
  17900. /** @hidden */
  17901. Node.prototype.hasNewParent = function (update) {
  17902. if (this._cache.parent === this.parent)
  17903. return false;
  17904. if (update)
  17905. this._cache.parent = this.parent;
  17906. return true;
  17907. };
  17908. /**
  17909. * Is this node ready to be used/rendered
  17910. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17911. * @return true if the node is ready
  17912. */
  17913. Node.prototype.isReady = function (completeCheck) {
  17914. if (completeCheck === void 0) { completeCheck = false; }
  17915. return this._isReady;
  17916. };
  17917. /**
  17918. * Is this node enabled?
  17919. * 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
  17920. * @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
  17921. * @return whether this node (and its parent) is enabled
  17922. */
  17923. Node.prototype.isEnabled = function (checkAncestors) {
  17924. if (checkAncestors === void 0) { checkAncestors = true; }
  17925. if (checkAncestors === false) {
  17926. return this._isEnabled;
  17927. }
  17928. if (this._isEnabled === false) {
  17929. return false;
  17930. }
  17931. if (this.parent !== undefined && this.parent !== null) {
  17932. return this.parent.isEnabled(checkAncestors);
  17933. }
  17934. return true;
  17935. };
  17936. /**
  17937. * Set the enabled state of this node
  17938. * @param value defines the new enabled state
  17939. */
  17940. Node.prototype.setEnabled = function (value) {
  17941. this._isEnabled = value;
  17942. };
  17943. /**
  17944. * Is this node a descendant of the given node?
  17945. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17946. * @param ancestor defines the parent node to inspect
  17947. * @returns a boolean indicating if this node is a descendant of the given node
  17948. */
  17949. Node.prototype.isDescendantOf = function (ancestor) {
  17950. if (this.parent) {
  17951. if (this.parent === ancestor) {
  17952. return true;
  17953. }
  17954. return this.parent.isDescendantOf(ancestor);
  17955. }
  17956. return false;
  17957. };
  17958. /** @hidden */
  17959. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17960. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17961. if (!this._children) {
  17962. return;
  17963. }
  17964. for (var index = 0; index < this._children.length; index++) {
  17965. var item = this._children[index];
  17966. if (!predicate || predicate(item)) {
  17967. results.push(item);
  17968. }
  17969. if (!directDescendantsOnly) {
  17970. item._getDescendants(results, false, predicate);
  17971. }
  17972. }
  17973. };
  17974. /**
  17975. * Will return all nodes that have this node as ascendant
  17976. * @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
  17977. * @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
  17978. * @return all children nodes of all types
  17979. */
  17980. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17981. var results = new Array();
  17982. this._getDescendants(results, directDescendantsOnly, predicate);
  17983. return results;
  17984. };
  17985. /**
  17986. * Get all child-meshes of this node
  17987. * @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
  17988. * @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
  17989. * @returns an array of {BABYLON.AbstractMesh}
  17990. */
  17991. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17992. var results = [];
  17993. this._getDescendants(results, directDescendantsOnly, function (node) {
  17994. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17995. });
  17996. return results;
  17997. };
  17998. /**
  17999. * Get all child-transformNodes of this node
  18000. * @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
  18001. * @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
  18002. * @returns an array of {BABYLON.TransformNode}
  18003. */
  18004. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18005. var results = [];
  18006. this._getDescendants(results, directDescendantsOnly, function (node) {
  18007. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18008. });
  18009. return results;
  18010. };
  18011. /**
  18012. * Get all direct children of this node
  18013. * @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
  18014. * @returns an array of {BABYLON.Node}
  18015. */
  18016. Node.prototype.getChildren = function (predicate) {
  18017. return this.getDescendants(true, predicate);
  18018. };
  18019. /** @hidden */
  18020. Node.prototype._setReady = function (state) {
  18021. if (state === this._isReady) {
  18022. return;
  18023. }
  18024. if (!state) {
  18025. this._isReady = false;
  18026. return;
  18027. }
  18028. if (this.onReady) {
  18029. this.onReady(this);
  18030. }
  18031. this._isReady = true;
  18032. };
  18033. /**
  18034. * Get an animation by name
  18035. * @param name defines the name of the animation to look for
  18036. * @returns null if not found else the requested animation
  18037. */
  18038. Node.prototype.getAnimationByName = function (name) {
  18039. for (var i = 0; i < this.animations.length; i++) {
  18040. var animation = this.animations[i];
  18041. if (animation.name === name) {
  18042. return animation;
  18043. }
  18044. }
  18045. return null;
  18046. };
  18047. /**
  18048. * Creates an animation range for this node
  18049. * @param name defines the name of the range
  18050. * @param from defines the starting key
  18051. * @param to defines the end key
  18052. */
  18053. Node.prototype.createAnimationRange = function (name, from, to) {
  18054. // check name not already in use
  18055. if (!this._ranges[name]) {
  18056. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18057. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18058. if (this.animations[i]) {
  18059. this.animations[i].createRange(name, from, to);
  18060. }
  18061. }
  18062. }
  18063. };
  18064. /**
  18065. * Delete a specific animation range
  18066. * @param name defines the name of the range to delete
  18067. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18068. */
  18069. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18070. if (deleteFrames === void 0) { deleteFrames = true; }
  18071. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18072. if (this.animations[i]) {
  18073. this.animations[i].deleteRange(name, deleteFrames);
  18074. }
  18075. }
  18076. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18077. };
  18078. /**
  18079. * Get an animation range by name
  18080. * @param name defines the name of the animation range to look for
  18081. * @returns null if not found else the requested animation range
  18082. */
  18083. Node.prototype.getAnimationRange = function (name) {
  18084. return this._ranges[name];
  18085. };
  18086. /**
  18087. * Will start the animation sequence
  18088. * @param name defines the range frames for animation sequence
  18089. * @param loop defines if the animation should loop (false by default)
  18090. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18091. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18092. * @returns the object created for this animation. If range does not exist, it will return null
  18093. */
  18094. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18095. var range = this.getAnimationRange(name);
  18096. if (!range) {
  18097. return null;
  18098. }
  18099. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18100. };
  18101. /**
  18102. * Serialize animation ranges into a JSON compatible object
  18103. * @returns serialization object
  18104. */
  18105. Node.prototype.serializeAnimationRanges = function () {
  18106. var serializationRanges = [];
  18107. for (var name in this._ranges) {
  18108. var localRange = this._ranges[name];
  18109. if (!localRange) {
  18110. continue;
  18111. }
  18112. var range = {};
  18113. range.name = name;
  18114. range.from = localRange.from;
  18115. range.to = localRange.to;
  18116. serializationRanges.push(range);
  18117. }
  18118. return serializationRanges;
  18119. };
  18120. /**
  18121. * Computes the world matrix of the node
  18122. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18123. * @returns the world matrix
  18124. */
  18125. Node.prototype.computeWorldMatrix = function (force) {
  18126. return BABYLON.Matrix.Identity();
  18127. };
  18128. /**
  18129. * Releases resources associated with this node.
  18130. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18131. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18132. */
  18133. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18134. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18135. if (!doNotRecurse) {
  18136. var nodes = this.getDescendants(true);
  18137. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18138. var node = nodes_1[_i];
  18139. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18140. }
  18141. }
  18142. else {
  18143. var transformNodes = this.getChildTransformNodes(true);
  18144. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18145. var transformNode = transformNodes_1[_a];
  18146. transformNode.parent = null;
  18147. transformNode.computeWorldMatrix(true);
  18148. }
  18149. }
  18150. this.parent = null;
  18151. // Callback
  18152. this.onDisposeObservable.notifyObservers(this);
  18153. this.onDisposeObservable.clear();
  18154. // Behaviors
  18155. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18156. var behavior = _c[_b];
  18157. behavior.detach();
  18158. }
  18159. this._behaviors = [];
  18160. this._isDisposed = true;
  18161. };
  18162. /**
  18163. * Parse animation range data from a serialization object and store them into a given node
  18164. * @param node defines where to store the animation ranges
  18165. * @param parsedNode defines the serialization object to read data from
  18166. * @param scene defines the hosting scene
  18167. */
  18168. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18169. if (parsedNode.ranges) {
  18170. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18171. var data = parsedNode.ranges[index];
  18172. node.createAnimationRange(data.name, data.from, data.to);
  18173. }
  18174. }
  18175. };
  18176. __decorate([
  18177. BABYLON.serialize()
  18178. ], Node.prototype, "name", void 0);
  18179. __decorate([
  18180. BABYLON.serialize()
  18181. ], Node.prototype, "id", void 0);
  18182. __decorate([
  18183. BABYLON.serialize()
  18184. ], Node.prototype, "uniqueId", void 0);
  18185. __decorate([
  18186. BABYLON.serialize()
  18187. ], Node.prototype, "state", void 0);
  18188. __decorate([
  18189. BABYLON.serialize()
  18190. ], Node.prototype, "metadata", void 0);
  18191. return Node;
  18192. }());
  18193. BABYLON.Node = Node;
  18194. })(BABYLON || (BABYLON = {}));
  18195. //# sourceMappingURL=babylon.node.js.map
  18196. var BABYLON;
  18197. (function (BABYLON) {
  18198. var BoundingSphere = /** @class */ (function () {
  18199. /**
  18200. * Creates a new bounding sphere
  18201. * @param min defines the minimum vector (in local space)
  18202. * @param max defines the maximum vector (in local space)
  18203. */
  18204. function BoundingSphere(min, max) {
  18205. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18206. this.reConstruct(min, max);
  18207. }
  18208. /**
  18209. * Recreates the entire bounding sphere from scratch
  18210. * @param min defines the new minimum vector (in local space)
  18211. * @param max defines the new maximum vector (in local space)
  18212. */
  18213. BoundingSphere.prototype.reConstruct = function (min, max) {
  18214. this.minimum = min.clone();
  18215. this.maximum = max.clone();
  18216. var distance = BABYLON.Vector3.Distance(min, max);
  18217. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18218. this.radius = distance * 0.5;
  18219. this.centerWorld = BABYLON.Vector3.Zero();
  18220. this._update(BABYLON.Matrix.Identity());
  18221. };
  18222. // Methods
  18223. BoundingSphere.prototype._update = function (world) {
  18224. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18225. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18226. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18227. };
  18228. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18229. for (var i = 0; i < 6; i++) {
  18230. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18231. return false;
  18232. }
  18233. return true;
  18234. };
  18235. BoundingSphere.prototype.intersectsPoint = function (point) {
  18236. var x = this.centerWorld.x - point.x;
  18237. var y = this.centerWorld.y - point.y;
  18238. var z = this.centerWorld.z - point.z;
  18239. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18240. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18241. return false;
  18242. return true;
  18243. };
  18244. // Statics
  18245. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18246. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18247. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18248. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18249. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18250. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18251. return false;
  18252. return true;
  18253. };
  18254. return BoundingSphere;
  18255. }());
  18256. BABYLON.BoundingSphere = BoundingSphere;
  18257. })(BABYLON || (BABYLON = {}));
  18258. //# sourceMappingURL=babylon.boundingSphere.js.map
  18259. var BABYLON;
  18260. (function (BABYLON) {
  18261. var BoundingBox = /** @class */ (function () {
  18262. /**
  18263. * Creates a new bounding box
  18264. * @param min defines the minimum vector (in local space)
  18265. * @param max defines the maximum vector (in local space)
  18266. */
  18267. function BoundingBox(min, max) {
  18268. this.vectorsWorld = new Array();
  18269. this.reConstruct(min, max);
  18270. }
  18271. // Methods
  18272. /**
  18273. * Recreates the entire bounding box from scratch
  18274. * @param min defines the new minimum vector (in local space)
  18275. * @param max defines the new maximum vector (in local space)
  18276. */
  18277. BoundingBox.prototype.reConstruct = function (min, max) {
  18278. this.minimum = min.clone();
  18279. this.maximum = max.clone();
  18280. // Bounding vectors
  18281. this.vectors = new Array();
  18282. this.vectors.push(this.minimum.clone());
  18283. this.vectors.push(this.maximum.clone());
  18284. this.vectors.push(this.minimum.clone());
  18285. this.vectors[2].x = this.maximum.x;
  18286. this.vectors.push(this.minimum.clone());
  18287. this.vectors[3].y = this.maximum.y;
  18288. this.vectors.push(this.minimum.clone());
  18289. this.vectors[4].z = this.maximum.z;
  18290. this.vectors.push(this.maximum.clone());
  18291. this.vectors[5].z = this.minimum.z;
  18292. this.vectors.push(this.maximum.clone());
  18293. this.vectors[6].x = this.minimum.x;
  18294. this.vectors.push(this.maximum.clone());
  18295. this.vectors[7].y = this.minimum.y;
  18296. // OBB
  18297. this.center = this.maximum.add(this.minimum).scale(0.5);
  18298. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18299. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18300. // World
  18301. for (var index = 0; index < this.vectors.length; index++) {
  18302. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18303. }
  18304. this.minimumWorld = BABYLON.Vector3.Zero();
  18305. this.maximumWorld = BABYLON.Vector3.Zero();
  18306. this.centerWorld = BABYLON.Vector3.Zero();
  18307. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18308. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18309. };
  18310. BoundingBox.prototype.getWorldMatrix = function () {
  18311. return this._worldMatrix;
  18312. };
  18313. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18314. this._worldMatrix.copyFrom(matrix);
  18315. return this;
  18316. };
  18317. BoundingBox.prototype._update = function (world) {
  18318. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18319. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18320. for (var index = 0; index < this.vectors.length; index++) {
  18321. var v = this.vectorsWorld[index];
  18322. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18323. if (v.x < this.minimumWorld.x)
  18324. this.minimumWorld.x = v.x;
  18325. if (v.y < this.minimumWorld.y)
  18326. this.minimumWorld.y = v.y;
  18327. if (v.z < this.minimumWorld.z)
  18328. this.minimumWorld.z = v.z;
  18329. if (v.x > this.maximumWorld.x)
  18330. this.maximumWorld.x = v.x;
  18331. if (v.y > this.maximumWorld.y)
  18332. this.maximumWorld.y = v.y;
  18333. if (v.z > this.maximumWorld.z)
  18334. this.maximumWorld.z = v.z;
  18335. }
  18336. // Extend
  18337. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18338. this.extendSizeWorld.scaleInPlace(0.5);
  18339. // OBB
  18340. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18341. this.centerWorld.scaleInPlace(0.5);
  18342. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18343. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18344. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18345. this._worldMatrix = world;
  18346. };
  18347. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18348. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18349. };
  18350. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18351. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18352. };
  18353. BoundingBox.prototype.intersectsPoint = function (point) {
  18354. var delta = -BABYLON.Epsilon;
  18355. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18356. return false;
  18357. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18358. return false;
  18359. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18360. return false;
  18361. return true;
  18362. };
  18363. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18364. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18365. };
  18366. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18367. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18368. return false;
  18369. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18370. return false;
  18371. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18372. return false;
  18373. return true;
  18374. };
  18375. // Statics
  18376. BoundingBox.Intersects = function (box0, box1) {
  18377. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18378. return false;
  18379. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18380. return false;
  18381. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18382. return false;
  18383. return true;
  18384. };
  18385. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18386. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18387. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18388. return (num <= (sphereRadius * sphereRadius));
  18389. };
  18390. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18391. for (var p = 0; p < 6; p++) {
  18392. for (var i = 0; i < 8; i++) {
  18393. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18394. return false;
  18395. }
  18396. }
  18397. }
  18398. return true;
  18399. };
  18400. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18401. for (var p = 0; p < 6; p++) {
  18402. var inCount = 8;
  18403. for (var i = 0; i < 8; i++) {
  18404. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18405. --inCount;
  18406. }
  18407. else {
  18408. break;
  18409. }
  18410. }
  18411. if (inCount === 0)
  18412. return false;
  18413. }
  18414. return true;
  18415. };
  18416. return BoundingBox;
  18417. }());
  18418. BABYLON.BoundingBox = BoundingBox;
  18419. })(BABYLON || (BABYLON = {}));
  18420. //# sourceMappingURL=babylon.boundingBox.js.map
  18421. var BABYLON;
  18422. (function (BABYLON) {
  18423. var computeBoxExtents = function (axis, box) {
  18424. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18425. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18426. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18427. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18428. var r = r0 + r1 + r2;
  18429. return {
  18430. min: p - r,
  18431. max: p + r
  18432. };
  18433. };
  18434. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18435. var axisOverlap = function (axis, box0, box1) {
  18436. var result0 = computeBoxExtents(axis, box0);
  18437. var result1 = computeBoxExtents(axis, box1);
  18438. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18439. };
  18440. var BoundingInfo = /** @class */ (function () {
  18441. function BoundingInfo(minimum, maximum) {
  18442. this.minimum = minimum;
  18443. this.maximum = maximum;
  18444. this._isLocked = false;
  18445. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18446. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18447. }
  18448. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18449. get: function () {
  18450. return this._isLocked;
  18451. },
  18452. set: function (value) {
  18453. this._isLocked = value;
  18454. },
  18455. enumerable: true,
  18456. configurable: true
  18457. });
  18458. // Methods
  18459. BoundingInfo.prototype.update = function (world) {
  18460. if (this._isLocked) {
  18461. return;
  18462. }
  18463. this.boundingBox._update(world);
  18464. this.boundingSphere._update(world);
  18465. };
  18466. /**
  18467. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18468. * @param center New center of the bounding info
  18469. * @param extend New extend of the bounding info
  18470. */
  18471. BoundingInfo.prototype.centerOn = function (center, extend) {
  18472. this.minimum = center.subtract(extend);
  18473. this.maximum = center.add(extend);
  18474. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18475. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18476. return this;
  18477. };
  18478. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18479. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18480. return false;
  18481. return this.boundingBox.isInFrustum(frustumPlanes);
  18482. };
  18483. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18484. /**
  18485. * Gets the world distance between the min and max points of the bounding box
  18486. */
  18487. get: function () {
  18488. var boundingBox = this.boundingBox;
  18489. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18490. return size.length();
  18491. },
  18492. enumerable: true,
  18493. configurable: true
  18494. });
  18495. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18496. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18497. };
  18498. BoundingInfo.prototype._checkCollision = function (collider) {
  18499. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18500. };
  18501. BoundingInfo.prototype.intersectsPoint = function (point) {
  18502. if (!this.boundingSphere.centerWorld) {
  18503. return false;
  18504. }
  18505. if (!this.boundingSphere.intersectsPoint(point)) {
  18506. return false;
  18507. }
  18508. if (!this.boundingBox.intersectsPoint(point)) {
  18509. return false;
  18510. }
  18511. return true;
  18512. };
  18513. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18514. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18515. return false;
  18516. }
  18517. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18518. return false;
  18519. }
  18520. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18521. return false;
  18522. }
  18523. if (!precise) {
  18524. return true;
  18525. }
  18526. var box0 = this.boundingBox;
  18527. var box1 = boundingInfo.boundingBox;
  18528. if (!axisOverlap(box0.directions[0], box0, box1))
  18529. return false;
  18530. if (!axisOverlap(box0.directions[1], box0, box1))
  18531. return false;
  18532. if (!axisOverlap(box0.directions[2], box0, box1))
  18533. return false;
  18534. if (!axisOverlap(box1.directions[0], box0, box1))
  18535. return false;
  18536. if (!axisOverlap(box1.directions[1], box0, box1))
  18537. return false;
  18538. if (!axisOverlap(box1.directions[2], box0, box1))
  18539. return false;
  18540. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18541. return false;
  18542. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18543. return false;
  18544. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18545. return false;
  18546. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18547. return false;
  18548. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18549. return false;
  18550. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18551. return false;
  18552. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18553. return false;
  18554. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18555. return false;
  18556. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18557. return false;
  18558. return true;
  18559. };
  18560. return BoundingInfo;
  18561. }());
  18562. BABYLON.BoundingInfo = BoundingInfo;
  18563. })(BABYLON || (BABYLON = {}));
  18564. //# sourceMappingURL=babylon.boundingInfo.js.map
  18565. var BABYLON;
  18566. (function (BABYLON) {
  18567. var TransformNode = /** @class */ (function (_super) {
  18568. __extends(TransformNode, _super);
  18569. function TransformNode(name, scene, isPure) {
  18570. if (scene === void 0) { scene = null; }
  18571. if (isPure === void 0) { isPure = true; }
  18572. var _this = _super.call(this, name, scene) || this;
  18573. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18574. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18575. _this._up = new BABYLON.Vector3(0, 1, 0);
  18576. _this._right = new BABYLON.Vector3(1, 0, 0);
  18577. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18578. // Properties
  18579. _this._rotation = BABYLON.Vector3.Zero();
  18580. _this._scaling = BABYLON.Vector3.One();
  18581. _this._isDirty = false;
  18582. /**
  18583. * Set the billboard mode. Default is 0.
  18584. *
  18585. * | Value | Type | Description |
  18586. * | --- | --- | --- |
  18587. * | 0 | BILLBOARDMODE_NONE | |
  18588. * | 1 | BILLBOARDMODE_X | |
  18589. * | 2 | BILLBOARDMODE_Y | |
  18590. * | 4 | BILLBOARDMODE_Z | |
  18591. * | 7 | BILLBOARDMODE_ALL | |
  18592. *
  18593. */
  18594. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18595. _this.scalingDeterminant = 1;
  18596. _this.infiniteDistance = false;
  18597. /**
  18598. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18599. * By default the system will update normals to compensate
  18600. */
  18601. _this.ignoreNonUniformScaling = false;
  18602. _this.position = BABYLON.Vector3.Zero();
  18603. _this._localWorld = BABYLON.Matrix.Zero();
  18604. _this._worldMatrix = BABYLON.Matrix.Zero();
  18605. _this._worldMatrixDeterminant = 0;
  18606. _this._absolutePosition = BABYLON.Vector3.Zero();
  18607. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18608. _this._postMultiplyPivotMatrix = false;
  18609. _this._isWorldMatrixFrozen = false;
  18610. /**
  18611. * An event triggered after the world matrix is updated
  18612. */
  18613. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18614. _this._nonUniformScaling = false;
  18615. if (isPure) {
  18616. _this.getScene().addTransformNode(_this);
  18617. }
  18618. return _this;
  18619. }
  18620. /**
  18621. * Gets a string idenfifying the name of the class
  18622. * @returns "TransformNode" string
  18623. */
  18624. TransformNode.prototype.getClassName = function () {
  18625. return "TransformNode";
  18626. };
  18627. Object.defineProperty(TransformNode.prototype, "rotation", {
  18628. /**
  18629. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18630. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18631. * Default : (0.0, 0.0, 0.0)
  18632. */
  18633. get: function () {
  18634. return this._rotation;
  18635. },
  18636. set: function (newRotation) {
  18637. this._rotation = newRotation;
  18638. },
  18639. enumerable: true,
  18640. configurable: true
  18641. });
  18642. Object.defineProperty(TransformNode.prototype, "scaling", {
  18643. /**
  18644. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18645. * Default : (1.0, 1.0, 1.0)
  18646. */
  18647. get: function () {
  18648. return this._scaling;
  18649. },
  18650. /**
  18651. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18652. * Default : (1.0, 1.0, 1.0)
  18653. */
  18654. set: function (newScaling) {
  18655. this._scaling = newScaling;
  18656. },
  18657. enumerable: true,
  18658. configurable: true
  18659. });
  18660. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18661. /**
  18662. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18663. * It's null by default.
  18664. * 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)
  18665. */
  18666. get: function () {
  18667. return this._rotationQuaternion;
  18668. },
  18669. set: function (quaternion) {
  18670. this._rotationQuaternion = quaternion;
  18671. //reset the rotation vector.
  18672. if (quaternion && this.rotation.length()) {
  18673. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18674. }
  18675. },
  18676. enumerable: true,
  18677. configurable: true
  18678. });
  18679. Object.defineProperty(TransformNode.prototype, "forward", {
  18680. /**
  18681. * The forward direction of that transform in world space.
  18682. */
  18683. get: function () {
  18684. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18685. },
  18686. enumerable: true,
  18687. configurable: true
  18688. });
  18689. Object.defineProperty(TransformNode.prototype, "up", {
  18690. /**
  18691. * The up direction of that transform in world space.
  18692. */
  18693. get: function () {
  18694. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18695. },
  18696. enumerable: true,
  18697. configurable: true
  18698. });
  18699. Object.defineProperty(TransformNode.prototype, "right", {
  18700. /**
  18701. * The right direction of that transform in world space.
  18702. */
  18703. get: function () {
  18704. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18705. },
  18706. enumerable: true,
  18707. configurable: true
  18708. });
  18709. /**
  18710. * Returns the latest update of the World matrix
  18711. * Returns a Matrix.
  18712. */
  18713. TransformNode.prototype.getWorldMatrix = function () {
  18714. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18715. this.computeWorldMatrix();
  18716. }
  18717. return this._worldMatrix;
  18718. };
  18719. /** @hidden */
  18720. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18721. return this._worldMatrixDeterminant;
  18722. };
  18723. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18724. /**
  18725. * Returns directly the latest state of the mesh World matrix.
  18726. * A Matrix is returned.
  18727. */
  18728. get: function () {
  18729. return this._worldMatrix;
  18730. },
  18731. enumerable: true,
  18732. configurable: true
  18733. });
  18734. /**
  18735. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18736. * Returns the TransformNode.
  18737. */
  18738. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18739. this._poseMatrix.copyFrom(matrix);
  18740. return this;
  18741. };
  18742. /**
  18743. * Returns the mesh Pose matrix.
  18744. * Returned object : Matrix
  18745. */
  18746. TransformNode.prototype.getPoseMatrix = function () {
  18747. return this._poseMatrix;
  18748. };
  18749. TransformNode.prototype._isSynchronized = function () {
  18750. if (this._isDirty) {
  18751. return false;
  18752. }
  18753. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18754. return false;
  18755. if (this._cache.pivotMatrixUpdated) {
  18756. return false;
  18757. }
  18758. if (this.infiniteDistance) {
  18759. return false;
  18760. }
  18761. if (!this._cache.position.equals(this.position))
  18762. return false;
  18763. if (this.rotationQuaternion) {
  18764. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18765. return false;
  18766. }
  18767. if (!this._cache.rotation.equals(this.rotation))
  18768. return false;
  18769. if (!this._cache.scaling.equals(this.scaling))
  18770. return false;
  18771. return true;
  18772. };
  18773. TransformNode.prototype._initCache = function () {
  18774. _super.prototype._initCache.call(this);
  18775. this._cache.localMatrixUpdated = false;
  18776. this._cache.position = BABYLON.Vector3.Zero();
  18777. this._cache.scaling = BABYLON.Vector3.Zero();
  18778. this._cache.rotation = BABYLON.Vector3.Zero();
  18779. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18780. this._cache.billboardMode = -1;
  18781. };
  18782. TransformNode.prototype.markAsDirty = function (property) {
  18783. if (property === "rotation") {
  18784. this.rotationQuaternion = null;
  18785. }
  18786. this._currentRenderId = Number.MAX_VALUE;
  18787. this._isDirty = true;
  18788. return this;
  18789. };
  18790. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18791. /**
  18792. * Returns the current mesh absolute position.
  18793. * Retuns a Vector3.
  18794. */
  18795. get: function () {
  18796. return this._absolutePosition;
  18797. },
  18798. enumerable: true,
  18799. configurable: true
  18800. });
  18801. /**
  18802. * Sets a new matrix to apply before all other transformation
  18803. * @param matrix defines the transform matrix
  18804. * @returns the current TransformNode
  18805. */
  18806. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18807. return this.setPivotMatrix(matrix, false);
  18808. };
  18809. /**
  18810. * Sets a new pivot matrix to the current node
  18811. * @param matrix defines the new pivot matrix to use
  18812. * @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
  18813. * @returns the current TransformNode
  18814. */
  18815. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18816. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18817. this._pivotMatrix = matrix.clone();
  18818. this._cache.pivotMatrixUpdated = true;
  18819. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18820. if (this._postMultiplyPivotMatrix) {
  18821. if (!this._pivotMatrixInverse) {
  18822. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18823. }
  18824. else {
  18825. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18826. }
  18827. }
  18828. return this;
  18829. };
  18830. /**
  18831. * Returns the mesh pivot matrix.
  18832. * Default : Identity.
  18833. * A Matrix is returned.
  18834. */
  18835. TransformNode.prototype.getPivotMatrix = function () {
  18836. return this._pivotMatrix;
  18837. };
  18838. /**
  18839. * Prevents the World matrix to be computed any longer.
  18840. * Returns the TransformNode.
  18841. */
  18842. TransformNode.prototype.freezeWorldMatrix = function () {
  18843. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18844. this.computeWorldMatrix(true);
  18845. this._isWorldMatrixFrozen = true;
  18846. return this;
  18847. };
  18848. /**
  18849. * Allows back the World matrix computation.
  18850. * Returns the TransformNode.
  18851. */
  18852. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18853. this._isWorldMatrixFrozen = false;
  18854. this.computeWorldMatrix(true);
  18855. return this;
  18856. };
  18857. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18858. /**
  18859. * True if the World matrix has been frozen.
  18860. * Returns a boolean.
  18861. */
  18862. get: function () {
  18863. return this._isWorldMatrixFrozen;
  18864. },
  18865. enumerable: true,
  18866. configurable: true
  18867. });
  18868. /**
  18869. * Retuns the mesh absolute position in the World.
  18870. * Returns a Vector3.
  18871. */
  18872. TransformNode.prototype.getAbsolutePosition = function () {
  18873. this.computeWorldMatrix();
  18874. return this._absolutePosition;
  18875. };
  18876. /**
  18877. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18878. * Returns the TransformNode.
  18879. */
  18880. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18881. if (!absolutePosition) {
  18882. return this;
  18883. }
  18884. var absolutePositionX;
  18885. var absolutePositionY;
  18886. var absolutePositionZ;
  18887. if (absolutePosition.x === undefined) {
  18888. if (arguments.length < 3) {
  18889. return this;
  18890. }
  18891. absolutePositionX = arguments[0];
  18892. absolutePositionY = arguments[1];
  18893. absolutePositionZ = arguments[2];
  18894. }
  18895. else {
  18896. absolutePositionX = absolutePosition.x;
  18897. absolutePositionY = absolutePosition.y;
  18898. absolutePositionZ = absolutePosition.z;
  18899. }
  18900. if (this.parent) {
  18901. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18902. invertParentWorldMatrix.invert();
  18903. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18904. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18905. }
  18906. else {
  18907. this.position.x = absolutePositionX;
  18908. this.position.y = absolutePositionY;
  18909. this.position.z = absolutePositionZ;
  18910. }
  18911. return this;
  18912. };
  18913. /**
  18914. * Sets the mesh position in its local space.
  18915. * Returns the TransformNode.
  18916. */
  18917. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18918. this.computeWorldMatrix();
  18919. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18920. return this;
  18921. };
  18922. /**
  18923. * Returns the mesh position in the local space from the current World matrix values.
  18924. * Returns a new Vector3.
  18925. */
  18926. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18927. this.computeWorldMatrix();
  18928. var invLocalWorldMatrix = this._localWorld.clone();
  18929. invLocalWorldMatrix.invert();
  18930. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18931. };
  18932. /**
  18933. * Translates the mesh along the passed Vector3 in its local space.
  18934. * Returns the TransformNode.
  18935. */
  18936. TransformNode.prototype.locallyTranslate = function (vector3) {
  18937. this.computeWorldMatrix(true);
  18938. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18939. return this;
  18940. };
  18941. /**
  18942. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18943. * @param targetPoint the position (must be in same space as current mesh) to look at
  18944. * @param yawCor optional yaw (y-axis) correction in radians
  18945. * @param pitchCor optional pitch (x-axis) correction in radians
  18946. * @param rollCor optional roll (z-axis) correction in radians
  18947. * @param space the choosen space of the target
  18948. * @returns the TransformNode.
  18949. */
  18950. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18951. if (yawCor === void 0) { yawCor = 0; }
  18952. if (pitchCor === void 0) { pitchCor = 0; }
  18953. if (rollCor === void 0) { rollCor = 0; }
  18954. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18955. var dv = TransformNode._lookAtVectorCache;
  18956. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18957. targetPoint.subtractToRef(pos, dv);
  18958. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18959. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18960. var pitch = Math.atan2(dv.y, len);
  18961. if (this.rotationQuaternion) {
  18962. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18963. }
  18964. else {
  18965. this.rotation.x = pitch + pitchCor;
  18966. this.rotation.y = yaw + yawCor;
  18967. this.rotation.z = rollCor;
  18968. }
  18969. return this;
  18970. };
  18971. /**
  18972. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18973. * This Vector3 is expressed in the World space.
  18974. */
  18975. TransformNode.prototype.getDirection = function (localAxis) {
  18976. var result = BABYLON.Vector3.Zero();
  18977. this.getDirectionToRef(localAxis, result);
  18978. return result;
  18979. };
  18980. /**
  18981. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18982. * localAxis is expressed in the mesh local space.
  18983. * result is computed in the Wordl space from the mesh World matrix.
  18984. * Returns the TransformNode.
  18985. */
  18986. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18987. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18988. return this;
  18989. };
  18990. /**
  18991. * Sets a new pivot point to the current node
  18992. * @param point defines the new pivot point to use
  18993. * @param space defines if the point is in world or local space (local by default)
  18994. * @returns the current TransformNode
  18995. */
  18996. TransformNode.prototype.setPivotPoint = function (point, space) {
  18997. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18998. if (this.getScene().getRenderId() == 0) {
  18999. this.computeWorldMatrix(true);
  19000. }
  19001. var wm = this.getWorldMatrix();
  19002. if (space == BABYLON.Space.WORLD) {
  19003. var tmat = BABYLON.Tmp.Matrix[0];
  19004. wm.invertToRef(tmat);
  19005. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19006. }
  19007. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19008. };
  19009. /**
  19010. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19011. */
  19012. TransformNode.prototype.getPivotPoint = function () {
  19013. var point = BABYLON.Vector3.Zero();
  19014. this.getPivotPointToRef(point);
  19015. return point;
  19016. };
  19017. /**
  19018. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19019. * Returns the TransformNode.
  19020. */
  19021. TransformNode.prototype.getPivotPointToRef = function (result) {
  19022. result.x = -this._pivotMatrix.m[12];
  19023. result.y = -this._pivotMatrix.m[13];
  19024. result.z = -this._pivotMatrix.m[14];
  19025. return this;
  19026. };
  19027. /**
  19028. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19029. */
  19030. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19031. var point = BABYLON.Vector3.Zero();
  19032. this.getAbsolutePivotPointToRef(point);
  19033. return point;
  19034. };
  19035. /**
  19036. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19037. * Returns the TransformNode.
  19038. */
  19039. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19040. result.x = this._pivotMatrix.m[12];
  19041. result.y = this._pivotMatrix.m[13];
  19042. result.z = this._pivotMatrix.m[14];
  19043. this.getPivotPointToRef(result);
  19044. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19045. return this;
  19046. };
  19047. /**
  19048. * Defines the passed node as the parent of the current node.
  19049. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19050. * Returns the TransformNode.
  19051. */
  19052. TransformNode.prototype.setParent = function (node) {
  19053. if (!node && !this.parent) {
  19054. return this;
  19055. }
  19056. if (!node) {
  19057. var rotation = BABYLON.Tmp.Quaternion[0];
  19058. var position = BABYLON.Tmp.Vector3[0];
  19059. var scale = BABYLON.Tmp.Vector3[1];
  19060. if (this.parent && this.parent.computeWorldMatrix) {
  19061. this.parent.computeWorldMatrix(true);
  19062. }
  19063. this.computeWorldMatrix(true);
  19064. this.getWorldMatrix().decompose(scale, rotation, position);
  19065. if (this.rotationQuaternion) {
  19066. this.rotationQuaternion.copyFrom(rotation);
  19067. }
  19068. else {
  19069. rotation.toEulerAnglesToRef(this.rotation);
  19070. }
  19071. this.scaling.x = scale.x;
  19072. this.scaling.y = scale.y;
  19073. this.scaling.z = scale.z;
  19074. this.position.x = position.x;
  19075. this.position.y = position.y;
  19076. this.position.z = position.z;
  19077. }
  19078. else {
  19079. var rotation = BABYLON.Tmp.Quaternion[0];
  19080. var position = BABYLON.Tmp.Vector3[0];
  19081. var scale = BABYLON.Tmp.Vector3[1];
  19082. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19083. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19084. this.computeWorldMatrix(true);
  19085. node.computeWorldMatrix(true);
  19086. node.getWorldMatrix().invertToRef(invParentMatrix);
  19087. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19088. diffMatrix.decompose(scale, rotation, position);
  19089. if (this.rotationQuaternion) {
  19090. this.rotationQuaternion.copyFrom(rotation);
  19091. }
  19092. else {
  19093. rotation.toEulerAnglesToRef(this.rotation);
  19094. }
  19095. this.position.x = position.x;
  19096. this.position.y = position.y;
  19097. this.position.z = position.z;
  19098. this.scaling.x = scale.x;
  19099. this.scaling.y = scale.y;
  19100. this.scaling.z = scale.z;
  19101. }
  19102. this.parent = node;
  19103. return this;
  19104. };
  19105. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19106. get: function () {
  19107. return this._nonUniformScaling;
  19108. },
  19109. enumerable: true,
  19110. configurable: true
  19111. });
  19112. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19113. if (this._nonUniformScaling === value) {
  19114. return false;
  19115. }
  19116. this._nonUniformScaling = value;
  19117. return true;
  19118. };
  19119. /**
  19120. * Attach the current TransformNode to another TransformNode associated with a bone
  19121. * @param bone Bone affecting the TransformNode
  19122. * @param affectedTransformNode TransformNode associated with the bone
  19123. */
  19124. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19125. this._transformToBoneReferal = affectedTransformNode;
  19126. this.parent = bone;
  19127. if (bone.getWorldMatrix().determinant() < 0) {
  19128. this.scalingDeterminant *= -1;
  19129. }
  19130. return this;
  19131. };
  19132. TransformNode.prototype.detachFromBone = function () {
  19133. if (!this.parent) {
  19134. return this;
  19135. }
  19136. if (this.parent.getWorldMatrix().determinant() < 0) {
  19137. this.scalingDeterminant *= -1;
  19138. }
  19139. this._transformToBoneReferal = null;
  19140. this.parent = null;
  19141. return this;
  19142. };
  19143. /**
  19144. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19145. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19146. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19147. * The passed axis is also normalized.
  19148. * Returns the TransformNode.
  19149. */
  19150. TransformNode.prototype.rotate = function (axis, amount, space) {
  19151. axis.normalize();
  19152. if (!this.rotationQuaternion) {
  19153. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19154. this.rotation = BABYLON.Vector3.Zero();
  19155. }
  19156. var rotationQuaternion;
  19157. if (!space || space === BABYLON.Space.LOCAL) {
  19158. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19159. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19160. }
  19161. else {
  19162. if (this.parent) {
  19163. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19164. invertParentWorldMatrix.invert();
  19165. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19166. }
  19167. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19168. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19169. }
  19170. return this;
  19171. };
  19172. /**
  19173. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19174. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19175. * The passed axis is also normalized.
  19176. * Returns the TransformNode.
  19177. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19178. */
  19179. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19180. axis.normalize();
  19181. if (!this.rotationQuaternion) {
  19182. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19183. this.rotation.copyFromFloats(0, 0, 0);
  19184. }
  19185. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19186. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19187. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19188. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19189. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19190. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19191. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19192. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19193. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19194. return this;
  19195. };
  19196. /**
  19197. * Translates the mesh along the axis vector for the passed distance in the given space.
  19198. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19199. * Returns the TransformNode.
  19200. */
  19201. TransformNode.prototype.translate = function (axis, distance, space) {
  19202. var displacementVector = axis.scale(distance);
  19203. if (!space || space === BABYLON.Space.LOCAL) {
  19204. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19205. this.setPositionWithLocalVector(tempV3);
  19206. }
  19207. else {
  19208. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19209. }
  19210. return this;
  19211. };
  19212. /**
  19213. * Adds a rotation step to the mesh current rotation.
  19214. * x, y, z are Euler angles expressed in radians.
  19215. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19216. * This means this rotation is made in the mesh local space only.
  19217. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19218. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19219. * ```javascript
  19220. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19221. * ```
  19222. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19223. * 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.
  19224. * Returns the TransformNode.
  19225. */
  19226. TransformNode.prototype.addRotation = function (x, y, z) {
  19227. var rotationQuaternion;
  19228. if (this.rotationQuaternion) {
  19229. rotationQuaternion = this.rotationQuaternion;
  19230. }
  19231. else {
  19232. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19233. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19234. }
  19235. var accumulation = BABYLON.Tmp.Quaternion[0];
  19236. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19237. rotationQuaternion.multiplyInPlace(accumulation);
  19238. if (!this.rotationQuaternion) {
  19239. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19240. }
  19241. return this;
  19242. };
  19243. /**
  19244. * Computes the mesh World matrix and returns it.
  19245. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19246. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19247. * If the parameter `force`is set to `true`, the actual computation is done.
  19248. * Returns the mesh World Matrix.
  19249. */
  19250. TransformNode.prototype.computeWorldMatrix = function (force) {
  19251. if (this._isWorldMatrixFrozen) {
  19252. return this._worldMatrix;
  19253. }
  19254. if (!force && this.isSynchronized(true)) {
  19255. this._currentRenderId = this.getScene().getRenderId();
  19256. return this._worldMatrix;
  19257. }
  19258. this._cache.position.copyFrom(this.position);
  19259. this._cache.scaling.copyFrom(this.scaling);
  19260. this._cache.pivotMatrixUpdated = false;
  19261. this._cache.billboardMode = this.billboardMode;
  19262. this._currentRenderId = this.getScene().getRenderId();
  19263. this._childRenderId = this.getScene().getRenderId();
  19264. this._isDirty = false;
  19265. // Scaling
  19266. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19267. // Rotation
  19268. //rotate, if quaternion is set and rotation was used
  19269. if (this.rotationQuaternion) {
  19270. var len = this.rotation.length();
  19271. if (len) {
  19272. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19273. this.rotation.copyFromFloats(0, 0, 0);
  19274. }
  19275. }
  19276. if (this.rotationQuaternion) {
  19277. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19278. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19279. }
  19280. else {
  19281. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19282. this._cache.rotation.copyFrom(this.rotation);
  19283. }
  19284. // Translation
  19285. var camera = this.getScene().activeCamera;
  19286. if (this.infiniteDistance && !this.parent && camera) {
  19287. var cameraWorldMatrix = camera.getWorldMatrix();
  19288. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19289. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19290. }
  19291. else {
  19292. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19293. }
  19294. // Composing transformations
  19295. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19296. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19297. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19298. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19299. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19300. // Need to decompose each rotation here
  19301. var currentPosition = BABYLON.Tmp.Vector3[3];
  19302. if (this.parent && this.parent.getWorldMatrix) {
  19303. if (this._transformToBoneReferal) {
  19304. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19305. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19306. }
  19307. else {
  19308. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19309. }
  19310. }
  19311. else {
  19312. currentPosition.copyFrom(this.position);
  19313. }
  19314. currentPosition.subtractInPlace(camera.globalPosition);
  19315. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19316. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19317. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19318. }
  19319. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19320. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19321. }
  19322. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19323. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19324. }
  19325. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19326. }
  19327. else {
  19328. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19329. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19330. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19331. }
  19332. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19333. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19334. }
  19335. // Local world
  19336. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19337. // Parent
  19338. if (this.parent && this.parent.getWorldMatrix) {
  19339. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19340. if (this._transformToBoneReferal) {
  19341. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19342. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19343. }
  19344. else {
  19345. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19346. }
  19347. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19348. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19349. this._worldMatrix.copyFrom(this._localWorld);
  19350. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19351. }
  19352. else {
  19353. if (this._transformToBoneReferal) {
  19354. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19355. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19356. }
  19357. else {
  19358. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19359. }
  19360. }
  19361. this._markSyncedWithParent();
  19362. }
  19363. else {
  19364. this._worldMatrix.copyFrom(this._localWorld);
  19365. }
  19366. // Post multiply inverse of pivotMatrix
  19367. if (this._postMultiplyPivotMatrix) {
  19368. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19369. }
  19370. // Normal matrix
  19371. if (!this.ignoreNonUniformScaling) {
  19372. if (this.scaling.isNonUniform) {
  19373. this._updateNonUniformScalingState(true);
  19374. }
  19375. else if (this.parent && this.parent._nonUniformScaling) {
  19376. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19377. }
  19378. else {
  19379. this._updateNonUniformScalingState(false);
  19380. }
  19381. }
  19382. else {
  19383. this._updateNonUniformScalingState(false);
  19384. }
  19385. this._afterComputeWorldMatrix();
  19386. // Absolute position
  19387. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19388. // Callbacks
  19389. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19390. if (!this._poseMatrix) {
  19391. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19392. }
  19393. // Cache the determinant
  19394. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19395. return this._worldMatrix;
  19396. };
  19397. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19398. };
  19399. /**
  19400. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19401. * @param func: callback function to add
  19402. *
  19403. * Returns the TransformNode.
  19404. */
  19405. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19406. this.onAfterWorldMatrixUpdateObservable.add(func);
  19407. return this;
  19408. };
  19409. /**
  19410. * Removes a registered callback function.
  19411. * Returns the TransformNode.
  19412. */
  19413. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19414. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19415. return this;
  19416. };
  19417. /**
  19418. * Clone the current transform node
  19419. * Returns the new transform node
  19420. * @param name Name of the new clone
  19421. * @param newParent New parent for the clone
  19422. * @param doNotCloneChildren Do not clone children hierarchy
  19423. */
  19424. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19425. var _this = this;
  19426. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19427. result.name = name;
  19428. result.id = name;
  19429. if (newParent) {
  19430. result.parent = newParent;
  19431. }
  19432. if (!doNotCloneChildren) {
  19433. // Children
  19434. var directDescendants = this.getDescendants(true);
  19435. for (var index = 0; index < directDescendants.length; index++) {
  19436. var child = directDescendants[index];
  19437. if (child.clone) {
  19438. child.clone(name + "." + child.name, result);
  19439. }
  19440. }
  19441. }
  19442. return result;
  19443. };
  19444. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19445. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19446. serializationObject.type = this.getClassName();
  19447. // Parent
  19448. if (this.parent) {
  19449. serializationObject.parentId = this.parent.id;
  19450. }
  19451. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19452. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19453. }
  19454. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19455. serializationObject.isEnabled = this.isEnabled();
  19456. // Parent
  19457. if (this.parent) {
  19458. serializationObject.parentId = this.parent.id;
  19459. }
  19460. return serializationObject;
  19461. };
  19462. // Statics
  19463. /**
  19464. * Returns a new TransformNode object parsed from the source provided.
  19465. * The parameter `parsedMesh` is the source.
  19466. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19467. */
  19468. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19469. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19470. if (BABYLON.Tags) {
  19471. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19472. }
  19473. if (parsedTransformNode.localMatrix) {
  19474. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19475. }
  19476. else if (parsedTransformNode.pivotMatrix) {
  19477. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19478. }
  19479. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19480. // Parent
  19481. if (parsedTransformNode.parentId) {
  19482. transformNode._waitingParentId = parsedTransformNode.parentId;
  19483. }
  19484. return transformNode;
  19485. };
  19486. /**
  19487. * Releases resources associated with this transform node.
  19488. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19489. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19490. */
  19491. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19492. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19493. // Animations
  19494. this.getScene().stopAnimation(this);
  19495. // Remove from scene
  19496. this.getScene().removeTransformNode(this);
  19497. this.onAfterWorldMatrixUpdateObservable.clear();
  19498. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19499. };
  19500. // Statics
  19501. TransformNode.BILLBOARDMODE_NONE = 0;
  19502. TransformNode.BILLBOARDMODE_X = 1;
  19503. TransformNode.BILLBOARDMODE_Y = 2;
  19504. TransformNode.BILLBOARDMODE_Z = 4;
  19505. TransformNode.BILLBOARDMODE_ALL = 7;
  19506. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19507. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19508. __decorate([
  19509. BABYLON.serializeAsVector3()
  19510. ], TransformNode.prototype, "_rotation", void 0);
  19511. __decorate([
  19512. BABYLON.serializeAsQuaternion()
  19513. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19514. __decorate([
  19515. BABYLON.serializeAsVector3()
  19516. ], TransformNode.prototype, "_scaling", void 0);
  19517. __decorate([
  19518. BABYLON.serialize()
  19519. ], TransformNode.prototype, "billboardMode", void 0);
  19520. __decorate([
  19521. BABYLON.serialize()
  19522. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19523. __decorate([
  19524. BABYLON.serialize()
  19525. ], TransformNode.prototype, "infiniteDistance", void 0);
  19526. __decorate([
  19527. BABYLON.serialize()
  19528. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19529. __decorate([
  19530. BABYLON.serializeAsVector3()
  19531. ], TransformNode.prototype, "position", void 0);
  19532. return TransformNode;
  19533. }(BABYLON.Node));
  19534. BABYLON.TransformNode = TransformNode;
  19535. })(BABYLON || (BABYLON = {}));
  19536. //# sourceMappingURL=babylon.transformNode.js.map
  19537. var BABYLON;
  19538. (function (BABYLON) {
  19539. /**
  19540. * Class used to store all common mesh properties
  19541. */
  19542. var AbstractMesh = /** @class */ (function (_super) {
  19543. __extends(AbstractMesh, _super);
  19544. // Constructor
  19545. /**
  19546. * Creates a new AbstractMesh
  19547. * @param name defines the name of the mesh
  19548. * @param scene defines the hosting scene
  19549. */
  19550. function AbstractMesh(name, scene) {
  19551. if (scene === void 0) { scene = null; }
  19552. var _this = _super.call(this, name, scene, false) || this;
  19553. _this._facetNb = 0; // facet number
  19554. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19555. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19556. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19557. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19558. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19559. _this._subDiv = {
  19560. max: 1,
  19561. X: 1,
  19562. Y: 1,
  19563. Z: 1
  19564. };
  19565. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19566. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19567. // Events
  19568. /**
  19569. * An event triggered when this mesh collides with another one
  19570. */
  19571. _this.onCollideObservable = new BABYLON.Observable();
  19572. /**
  19573. * An event triggered when the collision's position changes
  19574. */
  19575. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19576. /**
  19577. * An event triggered when material is changed
  19578. */
  19579. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19580. // Properties
  19581. /**
  19582. * Gets or sets the orientation for POV movement & rotation
  19583. */
  19584. _this.definedFacingForward = true;
  19585. /**
  19586. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19587. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19588. * * 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.
  19589. * @see http://doc.babylonjs.com/features/occlusionquery
  19590. */
  19591. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19592. /**
  19593. * 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:
  19594. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19595. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19596. * * 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.
  19597. * @see http://doc.babylonjs.com/features/occlusionquery
  19598. */
  19599. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19600. /**
  19601. * 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.
  19602. * The default value is -1 which means don't break the query and wait till the result
  19603. * @see http://doc.babylonjs.com/features/occlusionquery
  19604. */
  19605. _this.occlusionRetryCount = -1;
  19606. _this._occlusionInternalRetryCounter = 0;
  19607. _this._isOccluded = false;
  19608. _this._isOcclusionQueryInProgress = false;
  19609. _this._visibility = 1.0;
  19610. /** Gets or sets the alpha index used to sort transparent meshes
  19611. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19612. */
  19613. _this.alphaIndex = Number.MAX_VALUE;
  19614. /**
  19615. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19616. */
  19617. _this.isVisible = true;
  19618. /**
  19619. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19620. */
  19621. _this.isPickable = true;
  19622. /**
  19623. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19624. */
  19625. _this.showBoundingBox = false;
  19626. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19627. _this.showSubMeshesBoundingBox = false;
  19628. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19629. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19630. */
  19631. _this.isBlocker = false;
  19632. /**
  19633. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19634. */
  19635. _this.enablePointerMoveEvents = false;
  19636. /**
  19637. * Specifies the rendering group id for this mesh (0 by default)
  19638. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19639. */
  19640. _this.renderingGroupId = 0;
  19641. _this._receiveShadows = false;
  19642. /**
  19643. * Gets or sets a boolean indicating if the outline must be rendered as well
  19644. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19645. */
  19646. _this.renderOutline = false;
  19647. /** Defines color to use when rendering outline */
  19648. _this.outlineColor = BABYLON.Color3.Red();
  19649. /** Define width to use when rendering outline */
  19650. _this.outlineWidth = 0.02;
  19651. /**
  19652. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19653. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19654. */
  19655. _this.renderOverlay = false;
  19656. /** Defines color to use when rendering overlay */
  19657. _this.overlayColor = BABYLON.Color3.Red();
  19658. /** Defines alpha to use when rendering overlay */
  19659. _this.overlayAlpha = 0.5;
  19660. _this._hasVertexAlpha = false;
  19661. _this._useVertexColors = true;
  19662. _this._computeBonesUsingShaders = true;
  19663. _this._numBoneInfluencers = 4;
  19664. _this._applyFog = true;
  19665. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19666. _this.useOctreeForRenderingSelection = true;
  19667. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19668. _this.useOctreeForPicking = true;
  19669. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19670. _this.useOctreeForCollisions = true;
  19671. _this._layerMask = 0x0FFFFFFF;
  19672. /**
  19673. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19674. */
  19675. _this.alwaysSelectAsActiveMesh = false;
  19676. /**
  19677. * Gets or sets the current action manager
  19678. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19679. */
  19680. _this.actionManager = null;
  19681. /**
  19682. * Gets or sets impostor used for physic simulation
  19683. * @see http://doc.babylonjs.com/features/physics_engine
  19684. */
  19685. _this.physicsImpostor = null;
  19686. // Collisions
  19687. _this._checkCollisions = false;
  19688. _this._collisionMask = -1;
  19689. _this._collisionGroup = -1;
  19690. /**
  19691. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19692. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19693. */
  19694. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19695. /**
  19696. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19697. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19698. */
  19699. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19700. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19701. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19702. // Edges
  19703. /**
  19704. * Defines edge width used when edgesRenderer is enabled
  19705. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19706. */
  19707. _this.edgesWidth = 1;
  19708. /**
  19709. * Defines edge color used when edgesRenderer is enabled
  19710. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19711. */
  19712. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19713. // Cache
  19714. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19715. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19716. /** @hidden */
  19717. _this._renderId = 0;
  19718. /** @hidden */
  19719. _this._intersectionsInProgress = new Array();
  19720. /** @hidden */
  19721. _this._unIndexed = false;
  19722. /** @hidden */
  19723. _this._lightSources = new Array();
  19724. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19725. if (collidedMesh === void 0) { collidedMesh = null; }
  19726. //TODO move this to the collision coordinator!
  19727. if (_this.getScene().workerCollisions)
  19728. newPosition.multiplyInPlace(_this._collider._radius);
  19729. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19730. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19731. _this.position.addInPlace(_this._diffPositionForCollisions);
  19732. }
  19733. if (collidedMesh) {
  19734. _this.onCollideObservable.notifyObservers(collidedMesh);
  19735. }
  19736. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19737. };
  19738. _this.getScene().addMesh(_this);
  19739. _this._resyncLightSources();
  19740. return _this;
  19741. }
  19742. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19743. /**
  19744. * No billboard
  19745. */
  19746. get: function () {
  19747. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19748. },
  19749. enumerable: true,
  19750. configurable: true
  19751. });
  19752. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19753. /** Billboard on X axis */
  19754. get: function () {
  19755. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19756. },
  19757. enumerable: true,
  19758. configurable: true
  19759. });
  19760. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19761. /** Billboard on Y axis */
  19762. get: function () {
  19763. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19764. },
  19765. enumerable: true,
  19766. configurable: true
  19767. });
  19768. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19769. /** Billboard on Z axis */
  19770. get: function () {
  19771. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19772. },
  19773. enumerable: true,
  19774. configurable: true
  19775. });
  19776. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19777. /** Billboard on all axes */
  19778. get: function () {
  19779. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19785. /**
  19786. * Gets the number of facets in the mesh
  19787. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19788. */
  19789. get: function () {
  19790. return this._facetNb;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19796. /**
  19797. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19798. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19799. */
  19800. get: function () {
  19801. return this._partitioningSubdivisions;
  19802. },
  19803. set: function (nb) {
  19804. this._partitioningSubdivisions = nb;
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19810. /**
  19811. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19812. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19813. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19814. */
  19815. get: function () {
  19816. return this._partitioningBBoxRatio;
  19817. },
  19818. set: function (ratio) {
  19819. this._partitioningBBoxRatio = ratio;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19825. /**
  19826. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19827. * Works only for updatable meshes.
  19828. * Doesn't work with multi-materials
  19829. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19830. */
  19831. get: function () {
  19832. return this._facetDepthSort;
  19833. },
  19834. set: function (sort) {
  19835. this._facetDepthSort = sort;
  19836. },
  19837. enumerable: true,
  19838. configurable: true
  19839. });
  19840. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19841. /**
  19842. * The location (Vector3) where the facet depth sort must be computed from.
  19843. * By default, the active camera position.
  19844. * Used only when facet depth sort is enabled
  19845. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19846. */
  19847. get: function () {
  19848. return this._facetDepthSortFrom;
  19849. },
  19850. set: function (location) {
  19851. this._facetDepthSortFrom = location;
  19852. },
  19853. enumerable: true,
  19854. configurable: true
  19855. });
  19856. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19857. /**
  19858. * gets a boolean indicating if facetData is enabled
  19859. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19860. */
  19861. get: function () {
  19862. return this._facetDataEnabled;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. /** @hidden */
  19868. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19869. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19870. return false;
  19871. }
  19872. this._markSubMeshesAsMiscDirty();
  19873. return true;
  19874. };
  19875. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19876. /** Set a function to call when this mesh collides with another one */
  19877. set: function (callback) {
  19878. if (this._onCollideObserver) {
  19879. this.onCollideObservable.remove(this._onCollideObserver);
  19880. }
  19881. this._onCollideObserver = this.onCollideObservable.add(callback);
  19882. },
  19883. enumerable: true,
  19884. configurable: true
  19885. });
  19886. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19887. /** Set a function to call when the collision's position changes */
  19888. set: function (callback) {
  19889. if (this._onCollisionPositionChangeObserver) {
  19890. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19891. }
  19892. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19898. /**
  19899. * 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
  19900. * @see http://doc.babylonjs.com/features/occlusionquery
  19901. */
  19902. get: function () {
  19903. return this._isOccluded;
  19904. },
  19905. set: function (value) {
  19906. this._isOccluded = value;
  19907. },
  19908. enumerable: true,
  19909. configurable: true
  19910. });
  19911. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19912. /**
  19913. * Flag to check the progress status of the query
  19914. * @see http://doc.babylonjs.com/features/occlusionquery
  19915. */
  19916. get: function () {
  19917. return this._isOcclusionQueryInProgress;
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19923. /**
  19924. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19925. */
  19926. get: function () {
  19927. return this._visibility;
  19928. },
  19929. /**
  19930. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19931. */
  19932. set: function (value) {
  19933. if (this._visibility === value) {
  19934. return;
  19935. }
  19936. this._visibility = value;
  19937. this._markSubMeshesAsMiscDirty();
  19938. },
  19939. enumerable: true,
  19940. configurable: true
  19941. });
  19942. Object.defineProperty(AbstractMesh.prototype, "material", {
  19943. /** Gets or sets current material */
  19944. get: function () {
  19945. return this._material;
  19946. },
  19947. set: function (value) {
  19948. if (this._material === value) {
  19949. return;
  19950. }
  19951. this._material = value;
  19952. if (this.onMaterialChangedObservable.hasObservers) {
  19953. this.onMaterialChangedObservable.notifyObservers(this);
  19954. }
  19955. if (!this.subMeshes) {
  19956. return;
  19957. }
  19958. this._unBindEffect();
  19959. },
  19960. enumerable: true,
  19961. configurable: true
  19962. });
  19963. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19964. /**
  19965. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19966. * @see http://doc.babylonjs.com/babylon101/shadows
  19967. */
  19968. get: function () {
  19969. return this._receiveShadows;
  19970. },
  19971. set: function (value) {
  19972. if (this._receiveShadows === value) {
  19973. return;
  19974. }
  19975. this._receiveShadows = value;
  19976. this._markSubMeshesAsLightDirty();
  19977. },
  19978. enumerable: true,
  19979. configurable: true
  19980. });
  19981. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19982. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19983. get: function () {
  19984. return this._hasVertexAlpha;
  19985. },
  19986. set: function (value) {
  19987. if (this._hasVertexAlpha === value) {
  19988. return;
  19989. }
  19990. this._hasVertexAlpha = value;
  19991. this._markSubMeshesAsAttributesDirty();
  19992. this._markSubMeshesAsMiscDirty();
  19993. },
  19994. enumerable: true,
  19995. configurable: true
  19996. });
  19997. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19998. /** 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) */
  19999. get: function () {
  20000. return this._useVertexColors;
  20001. },
  20002. set: function (value) {
  20003. if (this._useVertexColors === value) {
  20004. return;
  20005. }
  20006. this._useVertexColors = value;
  20007. this._markSubMeshesAsAttributesDirty();
  20008. },
  20009. enumerable: true,
  20010. configurable: true
  20011. });
  20012. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20013. /**
  20014. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20015. */
  20016. get: function () {
  20017. return this._computeBonesUsingShaders;
  20018. },
  20019. set: function (value) {
  20020. if (this._computeBonesUsingShaders === value) {
  20021. return;
  20022. }
  20023. this._computeBonesUsingShaders = value;
  20024. this._markSubMeshesAsAttributesDirty();
  20025. },
  20026. enumerable: true,
  20027. configurable: true
  20028. });
  20029. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20030. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20031. get: function () {
  20032. return this._numBoneInfluencers;
  20033. },
  20034. set: function (value) {
  20035. if (this._numBoneInfluencers === value) {
  20036. return;
  20037. }
  20038. this._numBoneInfluencers = value;
  20039. this._markSubMeshesAsAttributesDirty();
  20040. },
  20041. enumerable: true,
  20042. configurable: true
  20043. });
  20044. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20045. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20046. get: function () {
  20047. return this._applyFog;
  20048. },
  20049. set: function (value) {
  20050. if (this._applyFog === value) {
  20051. return;
  20052. }
  20053. this._applyFog = value;
  20054. this._markSubMeshesAsMiscDirty();
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20060. /**
  20061. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20062. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20063. */
  20064. get: function () {
  20065. return this._layerMask;
  20066. },
  20067. set: function (value) {
  20068. if (value === this._layerMask) {
  20069. return;
  20070. }
  20071. this._layerMask = value;
  20072. this._resyncLightSources();
  20073. },
  20074. enumerable: true,
  20075. configurable: true
  20076. });
  20077. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20078. /**
  20079. * Gets or sets a collision mask used to mask collisions (default is -1).
  20080. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20081. */
  20082. get: function () {
  20083. return this._collisionMask;
  20084. },
  20085. set: function (mask) {
  20086. this._collisionMask = !isNaN(mask) ? mask : -1;
  20087. },
  20088. enumerable: true,
  20089. configurable: true
  20090. });
  20091. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20092. /**
  20093. * Gets or sets the current collision group mask (-1 by default).
  20094. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20095. */
  20096. get: function () {
  20097. return this._collisionGroup;
  20098. },
  20099. set: function (mask) {
  20100. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20101. },
  20102. enumerable: true,
  20103. configurable: true
  20104. });
  20105. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20106. /** @hidden */
  20107. get: function () {
  20108. return null;
  20109. },
  20110. enumerable: true,
  20111. configurable: true
  20112. });
  20113. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20114. get: function () {
  20115. return this._skeleton;
  20116. },
  20117. /**
  20118. * Gets or sets a skeleton to apply skining transformations
  20119. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20120. */
  20121. set: function (value) {
  20122. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20123. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20124. }
  20125. if (value && value.needInitialSkinMatrix) {
  20126. value._registerMeshWithPoseMatrix(this);
  20127. }
  20128. this._skeleton = value;
  20129. if (!this._skeleton) {
  20130. this._bonesTransformMatrices = null;
  20131. }
  20132. this._markSubMeshesAsAttributesDirty();
  20133. },
  20134. enumerable: true,
  20135. configurable: true
  20136. });
  20137. /**
  20138. * Returns the string "AbstractMesh"
  20139. * @returns "AbstractMesh"
  20140. */
  20141. AbstractMesh.prototype.getClassName = function () {
  20142. return "AbstractMesh";
  20143. };
  20144. /**
  20145. * Gets a string representation of the current mesh
  20146. * @param fullDetails defines a boolean indicating if full details must be included
  20147. * @returns a string representation of the current mesh
  20148. */
  20149. AbstractMesh.prototype.toString = function (fullDetails) {
  20150. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20151. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20152. if (this._skeleton) {
  20153. ret += ", skeleton: " + this._skeleton.name;
  20154. }
  20155. if (fullDetails) {
  20156. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20157. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20158. }
  20159. return ret;
  20160. };
  20161. /** @hidden */
  20162. AbstractMesh.prototype._rebuild = function () {
  20163. if (this._occlusionQuery) {
  20164. this._occlusionQuery = null;
  20165. }
  20166. if (this._edgesRenderer) {
  20167. this._edgesRenderer._rebuild();
  20168. }
  20169. if (!this.subMeshes) {
  20170. return;
  20171. }
  20172. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20173. var subMesh = _a[_i];
  20174. subMesh._rebuild();
  20175. }
  20176. };
  20177. /** @hidden */
  20178. AbstractMesh.prototype._resyncLightSources = function () {
  20179. this._lightSources.length = 0;
  20180. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20181. var light = _a[_i];
  20182. if (!light.isEnabled()) {
  20183. continue;
  20184. }
  20185. if (light.canAffectMesh(this)) {
  20186. this._lightSources.push(light);
  20187. }
  20188. }
  20189. this._markSubMeshesAsLightDirty();
  20190. };
  20191. /** @hidden */
  20192. AbstractMesh.prototype._resyncLighSource = function (light) {
  20193. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20194. var index = this._lightSources.indexOf(light);
  20195. if (index === -1) {
  20196. if (!isIn) {
  20197. return;
  20198. }
  20199. this._lightSources.push(light);
  20200. }
  20201. else {
  20202. if (isIn) {
  20203. return;
  20204. }
  20205. this._lightSources.splice(index, 1);
  20206. }
  20207. this._markSubMeshesAsLightDirty();
  20208. };
  20209. /** @hidden */
  20210. AbstractMesh.prototype._unBindEffect = function () {
  20211. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20212. var subMesh = _a[_i];
  20213. subMesh.setEffect(null);
  20214. }
  20215. };
  20216. /** @hidden */
  20217. AbstractMesh.prototype._removeLightSource = function (light) {
  20218. var index = this._lightSources.indexOf(light);
  20219. if (index === -1) {
  20220. return;
  20221. }
  20222. this._lightSources.splice(index, 1);
  20223. this._markSubMeshesAsLightDirty();
  20224. };
  20225. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20226. if (!this.subMeshes) {
  20227. return;
  20228. }
  20229. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20230. var subMesh = _a[_i];
  20231. if (subMesh._materialDefines) {
  20232. func(subMesh._materialDefines);
  20233. }
  20234. }
  20235. };
  20236. /** @hidden */
  20237. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20238. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20239. };
  20240. /** @hidden */
  20241. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20242. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20243. };
  20244. /** @hidden */
  20245. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20246. if (!this.subMeshes) {
  20247. return;
  20248. }
  20249. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20250. var subMesh = _a[_i];
  20251. var material = subMesh.getMaterial();
  20252. if (material) {
  20253. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20254. }
  20255. }
  20256. };
  20257. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20258. /**
  20259. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20260. */
  20261. get: function () {
  20262. return this._scaling;
  20263. },
  20264. set: function (newScaling) {
  20265. this._scaling = newScaling;
  20266. if (this.physicsImpostor) {
  20267. this.physicsImpostor.forceUpdate();
  20268. }
  20269. },
  20270. enumerable: true,
  20271. configurable: true
  20272. });
  20273. // Methods
  20274. /**
  20275. * Disables the mesh edge rendering mode
  20276. * @returns the currentAbstractMesh
  20277. */
  20278. AbstractMesh.prototype.disableEdgesRendering = function () {
  20279. if (this._edgesRenderer) {
  20280. this._edgesRenderer.dispose();
  20281. this._edgesRenderer = null;
  20282. }
  20283. return this;
  20284. };
  20285. /**
  20286. * Enables the edge rendering mode on the mesh.
  20287. * This mode makes the mesh edges visible
  20288. * @param epsilon defines the maximal distance between two angles to detect a face
  20289. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20290. * @returns the currentAbstractMesh
  20291. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20292. */
  20293. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20294. if (epsilon === void 0) { epsilon = 0.95; }
  20295. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20296. this.disableEdgesRendering();
  20297. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20298. return this;
  20299. };
  20300. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20301. /**
  20302. * Gets the edgesRenderer associated with the mesh
  20303. */
  20304. get: function () {
  20305. return this._edgesRenderer;
  20306. },
  20307. enumerable: true,
  20308. configurable: true
  20309. });
  20310. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20311. /**
  20312. * Returns true if the mesh is blocked. Implemented by child classes
  20313. */
  20314. get: function () {
  20315. return false;
  20316. },
  20317. enumerable: true,
  20318. configurable: true
  20319. });
  20320. /**
  20321. * Returns the mesh itself by default. Implemented by child classes
  20322. * @param camera defines the camera to use to pick the right LOD level
  20323. * @returns the currentAbstractMesh
  20324. */
  20325. AbstractMesh.prototype.getLOD = function (camera) {
  20326. return this;
  20327. };
  20328. /**
  20329. * Returns 0 by default. Implemented by child classes
  20330. * @returns an integer
  20331. */
  20332. AbstractMesh.prototype.getTotalVertices = function () {
  20333. return 0;
  20334. };
  20335. /**
  20336. * Returns null by default. Implemented by child classes
  20337. * @returns null
  20338. */
  20339. AbstractMesh.prototype.getIndices = function () {
  20340. return null;
  20341. };
  20342. /**
  20343. * Returns the array of the requested vertex data kind. Implemented by child classes
  20344. * @param kind defines the vertex data kind to use
  20345. * @returns null
  20346. */
  20347. AbstractMesh.prototype.getVerticesData = function (kind) {
  20348. return null;
  20349. };
  20350. /**
  20351. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20352. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20353. * Note that a new underlying VertexBuffer object is created each call.
  20354. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20355. * @param kind defines vertex data kind:
  20356. * * BABYLON.VertexBuffer.PositionKind
  20357. * * BABYLON.VertexBuffer.UVKind
  20358. * * BABYLON.VertexBuffer.UV2Kind
  20359. * * BABYLON.VertexBuffer.UV3Kind
  20360. * * BABYLON.VertexBuffer.UV4Kind
  20361. * * BABYLON.VertexBuffer.UV5Kind
  20362. * * BABYLON.VertexBuffer.UV6Kind
  20363. * * BABYLON.VertexBuffer.ColorKind
  20364. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20365. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20366. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20367. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20368. * @param data defines the data source
  20369. * @param updatable defines if the data must be flagged as updatable (or static)
  20370. * @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
  20371. * @returns the current mesh
  20372. */
  20373. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20374. return this;
  20375. };
  20376. /**
  20377. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20378. * If the mesh has no geometry, it is simply returned as it is.
  20379. * @param kind defines vertex data kind:
  20380. * * BABYLON.VertexBuffer.PositionKind
  20381. * * BABYLON.VertexBuffer.UVKind
  20382. * * BABYLON.VertexBuffer.UV2Kind
  20383. * * BABYLON.VertexBuffer.UV3Kind
  20384. * * BABYLON.VertexBuffer.UV4Kind
  20385. * * BABYLON.VertexBuffer.UV5Kind
  20386. * * BABYLON.VertexBuffer.UV6Kind
  20387. * * BABYLON.VertexBuffer.ColorKind
  20388. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20389. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20390. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20391. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20392. * @param data defines the data source
  20393. * @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
  20394. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20395. * @returns the current mesh
  20396. */
  20397. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20398. return this;
  20399. };
  20400. /**
  20401. * Sets the mesh indices,
  20402. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20403. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20404. * @param totalVertices Defines the total number of vertices
  20405. * @returns the current mesh
  20406. */
  20407. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20408. return this;
  20409. };
  20410. /**
  20411. * Gets a boolean indicating if specific vertex data is present
  20412. * @param kind defines the vertex data kind to use
  20413. * @returns true is data kind is present
  20414. */
  20415. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20416. return false;
  20417. };
  20418. /**
  20419. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20420. * @returns a BoundingInfo
  20421. */
  20422. AbstractMesh.prototype.getBoundingInfo = function () {
  20423. if (this._masterMesh) {
  20424. return this._masterMesh.getBoundingInfo();
  20425. }
  20426. if (!this._boundingInfo) {
  20427. // this._boundingInfo is being created here
  20428. this._updateBoundingInfo();
  20429. }
  20430. // cannot be null.
  20431. return this._boundingInfo;
  20432. };
  20433. /**
  20434. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20435. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20436. * @returns the current mesh
  20437. */
  20438. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20439. if (includeDescendants === void 0) { includeDescendants = true; }
  20440. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20441. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20442. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20443. if (maxDimension === 0) {
  20444. return this;
  20445. }
  20446. var scale = 1 / maxDimension;
  20447. this.scaling.scaleInPlace(scale);
  20448. return this;
  20449. };
  20450. /**
  20451. * Overwrite the current bounding info
  20452. * @param boundingInfo defines the new bounding info
  20453. * @returns the current mesh
  20454. */
  20455. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20456. this._boundingInfo = boundingInfo;
  20457. return this;
  20458. };
  20459. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20460. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20461. get: function () {
  20462. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20463. },
  20464. enumerable: true,
  20465. configurable: true
  20466. });
  20467. /** @hidden */
  20468. AbstractMesh.prototype._preActivate = function () {
  20469. };
  20470. /** @hidden */
  20471. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20472. };
  20473. /** @hidden */
  20474. AbstractMesh.prototype._activate = function (renderId) {
  20475. this._renderId = renderId;
  20476. };
  20477. /**
  20478. * Gets the current world matrix
  20479. * @returns a Matrix
  20480. */
  20481. AbstractMesh.prototype.getWorldMatrix = function () {
  20482. if (this._masterMesh) {
  20483. return this._masterMesh.getWorldMatrix();
  20484. }
  20485. return _super.prototype.getWorldMatrix.call(this);
  20486. };
  20487. /** @hidden */
  20488. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20489. if (this._masterMesh) {
  20490. return this._masterMesh._getWorldMatrixDeterminant();
  20491. }
  20492. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20493. };
  20494. // ================================== Point of View Movement =================================
  20495. /**
  20496. * Perform relative position change from the point of view of behind the front of the mesh.
  20497. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20498. * Supports definition of mesh facing forward or backward
  20499. * @param amountRight defines the distance on the right axis
  20500. * @param amountUp defines the distance on the up axis
  20501. * @param amountForward defines the distance on the forward axis
  20502. * @returns the current mesh
  20503. */
  20504. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20505. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20506. return this;
  20507. };
  20508. /**
  20509. * Calculate relative position change from the point of view of behind the front of the mesh.
  20510. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20511. * Supports definition of mesh facing forward or backward
  20512. * @param amountRight defines the distance on the right axis
  20513. * @param amountUp defines the distance on the up axis
  20514. * @param amountForward defines the distance on the forward axis
  20515. * @returns the new displacement vector
  20516. */
  20517. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20518. var rotMatrix = new BABYLON.Matrix();
  20519. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20520. rotQuaternion.toRotationMatrix(rotMatrix);
  20521. var translationDelta = BABYLON.Vector3.Zero();
  20522. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20523. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20524. return translationDelta;
  20525. };
  20526. // ================================== Point of View Rotation =================================
  20527. /**
  20528. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20529. * Supports definition of mesh facing forward or backward
  20530. * @param flipBack defines the flip
  20531. * @param twirlClockwise defines the twirl
  20532. * @param tiltRight defines the tilt
  20533. * @returns the current mesh
  20534. */
  20535. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20536. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20537. return this;
  20538. };
  20539. /**
  20540. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20541. * Supports definition of mesh facing forward or backward.
  20542. * @param flipBack defines the flip
  20543. * @param twirlClockwise defines the twirl
  20544. * @param tiltRight defines the tilt
  20545. * @returns the new rotation vector
  20546. */
  20547. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20548. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20549. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20550. };
  20551. /**
  20552. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20553. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20554. * @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
  20555. * @returns the new bounding vectors
  20556. */
  20557. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20558. if (includeDescendants === void 0) { includeDescendants = true; }
  20559. if (predicate === void 0) { predicate = null; }
  20560. // Ensures that all world matrix will be recomputed.
  20561. this.getScene().incrementRenderId();
  20562. this.computeWorldMatrix(true);
  20563. var min;
  20564. var max;
  20565. var boundingInfo = this.getBoundingInfo();
  20566. if (!this.subMeshes) {
  20567. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20568. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20569. }
  20570. else {
  20571. min = boundingInfo.boundingBox.minimumWorld;
  20572. max = boundingInfo.boundingBox.maximumWorld;
  20573. }
  20574. if (includeDescendants) {
  20575. var descendants = this.getDescendants(false);
  20576. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20577. var descendant = descendants_1[_i];
  20578. var childMesh = descendant;
  20579. childMesh.computeWorldMatrix(true);
  20580. // Filters meshes based on custom predicate function.
  20581. if (predicate && !predicate(childMesh)) {
  20582. continue;
  20583. }
  20584. //make sure we have the needed params to get mix and max
  20585. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20586. continue;
  20587. }
  20588. var childBoundingInfo = childMesh.getBoundingInfo();
  20589. var boundingBox = childBoundingInfo.boundingBox;
  20590. var minBox = boundingBox.minimumWorld;
  20591. var maxBox = boundingBox.maximumWorld;
  20592. BABYLON.Tools.CheckExtends(minBox, min, max);
  20593. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20594. }
  20595. }
  20596. return {
  20597. min: min,
  20598. max: max
  20599. };
  20600. };
  20601. /** @hidden */
  20602. AbstractMesh.prototype._updateBoundingInfo = function () {
  20603. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20604. this._boundingInfo.update(this.worldMatrixFromCache);
  20605. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20606. return this;
  20607. };
  20608. /** @hidden */
  20609. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20610. if (!this.subMeshes) {
  20611. return this;
  20612. }
  20613. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20614. var subMesh = this.subMeshes[subIndex];
  20615. if (!subMesh.IsGlobal) {
  20616. subMesh.updateBoundingInfo(matrix);
  20617. }
  20618. }
  20619. return this;
  20620. };
  20621. /** @hidden */
  20622. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20623. // Bounding info
  20624. this._updateBoundingInfo();
  20625. };
  20626. /**
  20627. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20628. * A mesh is in the frustum if its bounding box intersects the frustum
  20629. * @param frustumPlanes defines the frustum to test
  20630. * @returns true if the mesh is in the frustum planes
  20631. */
  20632. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20633. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20634. };
  20635. /**
  20636. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20637. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20638. * @param frustumPlanes defines the frustum to test
  20639. * @returns true if the mesh is completely in the frustum planes
  20640. */
  20641. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20642. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20643. };
  20644. /**
  20645. * True if the mesh intersects another mesh or a SolidParticle object
  20646. * @param mesh defines a target mesh or SolidParticle to test
  20647. * @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)
  20648. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20649. * @returns true if there is an intersection
  20650. */
  20651. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20652. if (precise === void 0) { precise = false; }
  20653. if (!this._boundingInfo || !mesh._boundingInfo) {
  20654. return false;
  20655. }
  20656. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20657. return true;
  20658. }
  20659. if (includeDescendants) {
  20660. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20661. var child = _a[_i];
  20662. if (child.intersectsMesh(mesh, precise, true)) {
  20663. return true;
  20664. }
  20665. }
  20666. }
  20667. return false;
  20668. };
  20669. /**
  20670. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20671. * @param point defines the point to test
  20672. * @returns true if there is an intersection
  20673. */
  20674. AbstractMesh.prototype.intersectsPoint = function (point) {
  20675. if (!this._boundingInfo) {
  20676. return false;
  20677. }
  20678. return this._boundingInfo.intersectsPoint(point);
  20679. };
  20680. /**
  20681. * Gets the current physics impostor
  20682. * @see http://doc.babylonjs.com/features/physics_engine
  20683. * @returns a physics impostor or null
  20684. */
  20685. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20686. return this.physicsImpostor;
  20687. };
  20688. /**
  20689. * Gets the position of the current mesh in camera space
  20690. * @param camera defines the camera to use
  20691. * @returns a position
  20692. */
  20693. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20694. if (camera === void 0) { camera = null; }
  20695. if (!camera) {
  20696. camera = this.getScene().activeCamera;
  20697. }
  20698. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20699. };
  20700. /**
  20701. * Returns the distance from the mesh to the active camera
  20702. * @param camera defines the camera to use
  20703. * @returns the distance
  20704. */
  20705. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20706. if (camera === void 0) { camera = null; }
  20707. if (!camera) {
  20708. camera = this.getScene().activeCamera;
  20709. }
  20710. return this.absolutePosition.subtract(camera.position).length();
  20711. };
  20712. /**
  20713. * Apply a physic impulse to the mesh
  20714. * @param force defines the force to apply
  20715. * @param contactPoint defines where to apply the force
  20716. * @returns the current mesh
  20717. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20718. */
  20719. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20720. if (!this.physicsImpostor) {
  20721. return this;
  20722. }
  20723. this.physicsImpostor.applyImpulse(force, contactPoint);
  20724. return this;
  20725. };
  20726. /**
  20727. * Creates a physic joint between two meshes
  20728. * @param otherMesh defines the other mesh to use
  20729. * @param pivot1 defines the pivot to use on this mesh
  20730. * @param pivot2 defines the pivot to use on the other mesh
  20731. * @param options defines additional options (can be plugin dependent)
  20732. * @returns the current mesh
  20733. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20734. */
  20735. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20736. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20737. return this;
  20738. }
  20739. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20740. mainPivot: pivot1,
  20741. connectedPivot: pivot2,
  20742. nativeParams: options
  20743. });
  20744. return this;
  20745. };
  20746. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20747. // Collisions
  20748. /**
  20749. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20750. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20751. */
  20752. get: function () {
  20753. return this._checkCollisions;
  20754. },
  20755. set: function (collisionEnabled) {
  20756. this._checkCollisions = collisionEnabled;
  20757. if (this.getScene().workerCollisions) {
  20758. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20759. }
  20760. },
  20761. enumerable: true,
  20762. configurable: true
  20763. });
  20764. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20765. /**
  20766. * Gets Collider object used to compute collisions (not physics)
  20767. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20768. */
  20769. get: function () {
  20770. return this._collider;
  20771. },
  20772. enumerable: true,
  20773. configurable: true
  20774. });
  20775. /**
  20776. * Move the mesh using collision engine
  20777. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20778. * @param displacement defines the requested displacement vector
  20779. * @returns the current mesh
  20780. */
  20781. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20782. var globalPosition = this.getAbsolutePosition();
  20783. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20784. if (!this._collider) {
  20785. this._collider = new BABYLON.Collider();
  20786. }
  20787. this._collider._radius = this.ellipsoid;
  20788. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20789. return this;
  20790. };
  20791. // Submeshes octree
  20792. /**
  20793. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20794. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20795. * @param maxCapacity defines the maximum size of each block (64 by default)
  20796. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20797. * @returns the new octree
  20798. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20799. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20800. */
  20801. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20802. if (maxCapacity === void 0) { maxCapacity = 64; }
  20803. if (maxDepth === void 0) { maxDepth = 2; }
  20804. if (!this._submeshesOctree) {
  20805. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20806. }
  20807. this.computeWorldMatrix(true);
  20808. var boundingInfo = this.getBoundingInfo();
  20809. // Update octree
  20810. var bbox = boundingInfo.boundingBox;
  20811. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20812. return this._submeshesOctree;
  20813. };
  20814. // Collisions
  20815. /** @hidden */
  20816. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20817. this._generatePointsArray();
  20818. if (!this._positions) {
  20819. return this;
  20820. }
  20821. // Transformation
  20822. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20823. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20824. subMesh._lastColliderWorldVertices = [];
  20825. subMesh._trianglePlanes = [];
  20826. var start = subMesh.verticesStart;
  20827. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20828. for (var i = start; i < end; i++) {
  20829. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20830. }
  20831. }
  20832. // Collide
  20833. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20834. if (collider.collisionFound) {
  20835. collider.collidedMesh = this;
  20836. }
  20837. return this;
  20838. };
  20839. /** @hidden */
  20840. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20841. var subMeshes;
  20842. var len;
  20843. // Octrees
  20844. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20845. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20846. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20847. len = intersections.length;
  20848. subMeshes = intersections.data;
  20849. }
  20850. else {
  20851. subMeshes = this.subMeshes;
  20852. len = subMeshes.length;
  20853. }
  20854. for (var index = 0; index < len; index++) {
  20855. var subMesh = subMeshes[index];
  20856. // Bounding test
  20857. if (len > 1 && !subMesh._checkCollision(collider))
  20858. continue;
  20859. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20860. }
  20861. return this;
  20862. };
  20863. /** @hidden */
  20864. AbstractMesh.prototype._checkCollision = function (collider) {
  20865. // Bounding box test
  20866. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20867. return this;
  20868. // Transformation matrix
  20869. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20870. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20871. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20872. return this;
  20873. };
  20874. // Picking
  20875. /** @hidden */
  20876. AbstractMesh.prototype._generatePointsArray = function () {
  20877. return false;
  20878. };
  20879. /**
  20880. * Checks if the passed Ray intersects with the mesh
  20881. * @param ray defines the ray to use
  20882. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20883. * @returns the picking info
  20884. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20885. */
  20886. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20887. var pickingInfo = new BABYLON.PickingInfo();
  20888. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20889. return pickingInfo;
  20890. }
  20891. if (!this._generatePointsArray()) {
  20892. return pickingInfo;
  20893. }
  20894. var intersectInfo = null;
  20895. // Octrees
  20896. var subMeshes;
  20897. var len;
  20898. if (this._submeshesOctree && this.useOctreeForPicking) {
  20899. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20900. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20901. len = intersections.length;
  20902. subMeshes = intersections.data;
  20903. }
  20904. else {
  20905. subMeshes = this.subMeshes;
  20906. len = subMeshes.length;
  20907. }
  20908. for (var index = 0; index < len; index++) {
  20909. var subMesh = subMeshes[index];
  20910. // Bounding test
  20911. if (len > 1 && !subMesh.canIntersects(ray))
  20912. continue;
  20913. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20914. if (currentIntersectInfo) {
  20915. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20916. intersectInfo = currentIntersectInfo;
  20917. intersectInfo.subMeshId = index;
  20918. if (fastCheck) {
  20919. break;
  20920. }
  20921. }
  20922. }
  20923. }
  20924. if (intersectInfo) {
  20925. // Get picked point
  20926. var world = this.getWorldMatrix();
  20927. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20928. var direction = ray.direction.clone();
  20929. direction = direction.scale(intersectInfo.distance);
  20930. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20931. var pickedPoint = worldOrigin.add(worldDirection);
  20932. // Return result
  20933. pickingInfo.hit = true;
  20934. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20935. pickingInfo.pickedPoint = pickedPoint;
  20936. pickingInfo.pickedMesh = this;
  20937. pickingInfo.bu = intersectInfo.bu || 0;
  20938. pickingInfo.bv = intersectInfo.bv || 0;
  20939. pickingInfo.faceId = intersectInfo.faceId;
  20940. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20941. return pickingInfo;
  20942. }
  20943. return pickingInfo;
  20944. };
  20945. /**
  20946. * Clones the current mesh
  20947. * @param name defines the mesh name
  20948. * @param newParent defines the new mesh parent
  20949. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20950. * @returns the new mesh
  20951. */
  20952. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20953. return null;
  20954. };
  20955. /**
  20956. * Disposes all the submeshes of the current meshnp
  20957. * @returns the current mesh
  20958. */
  20959. AbstractMesh.prototype.releaseSubMeshes = function () {
  20960. if (this.subMeshes) {
  20961. while (this.subMeshes.length) {
  20962. this.subMeshes[0].dispose();
  20963. }
  20964. }
  20965. else {
  20966. this.subMeshes = new Array();
  20967. }
  20968. return this;
  20969. };
  20970. /**
  20971. * Releases resources associated with this abstract mesh.
  20972. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20973. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20974. */
  20975. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20976. var _this = this;
  20977. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20978. var index;
  20979. // Smart Array Retainers.
  20980. this.getScene().freeActiveMeshes();
  20981. this.getScene().freeRenderingGroups();
  20982. // Action manager
  20983. if (this.actionManager !== undefined && this.actionManager !== null) {
  20984. this.actionManager.dispose();
  20985. this.actionManager = null;
  20986. }
  20987. // Skeleton
  20988. this._skeleton = null;
  20989. // Physics
  20990. if (this.physicsImpostor) {
  20991. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20992. }
  20993. // Intersections in progress
  20994. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20995. var other = this._intersectionsInProgress[index];
  20996. var pos = other._intersectionsInProgress.indexOf(this);
  20997. other._intersectionsInProgress.splice(pos, 1);
  20998. }
  20999. this._intersectionsInProgress = [];
  21000. // Lights
  21001. var lights = this.getScene().lights;
  21002. lights.forEach(function (light) {
  21003. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21004. if (meshIndex !== -1) {
  21005. light.includedOnlyMeshes.splice(meshIndex, 1);
  21006. }
  21007. meshIndex = light.excludedMeshes.indexOf(_this);
  21008. if (meshIndex !== -1) {
  21009. light.excludedMeshes.splice(meshIndex, 1);
  21010. }
  21011. // Shadow generators
  21012. var generator = light.getShadowGenerator();
  21013. if (generator) {
  21014. var shadowMap = generator.getShadowMap();
  21015. if (shadowMap && shadowMap.renderList) {
  21016. meshIndex = shadowMap.renderList.indexOf(_this);
  21017. if (meshIndex !== -1) {
  21018. shadowMap.renderList.splice(meshIndex, 1);
  21019. }
  21020. }
  21021. }
  21022. });
  21023. // Edges
  21024. if (this._edgesRenderer) {
  21025. this._edgesRenderer.dispose();
  21026. this._edgesRenderer = null;
  21027. }
  21028. // SubMeshes
  21029. if (this.getClassName() !== "InstancedMesh") {
  21030. this.releaseSubMeshes();
  21031. }
  21032. // Octree
  21033. var sceneOctree = this.getScene().selectionOctree;
  21034. if (sceneOctree !== undefined && sceneOctree !== null) {
  21035. var index = sceneOctree.dynamicContent.indexOf(this);
  21036. if (index !== -1) {
  21037. sceneOctree.dynamicContent.splice(index, 1);
  21038. }
  21039. }
  21040. // Query
  21041. var engine = this.getScene().getEngine();
  21042. if (this._occlusionQuery) {
  21043. this._isOcclusionQueryInProgress = false;
  21044. engine.deleteQuery(this._occlusionQuery);
  21045. this._occlusionQuery = null;
  21046. }
  21047. // Engine
  21048. engine.wipeCaches();
  21049. // Remove from scene
  21050. this.getScene().removeMesh(this);
  21051. if (disposeMaterialAndTextures) {
  21052. if (this.material) {
  21053. this.material.dispose(false, true);
  21054. }
  21055. }
  21056. if (!doNotRecurse) {
  21057. // Particles
  21058. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21059. if (this.getScene().particleSystems[index].emitter === this) {
  21060. this.getScene().particleSystems[index].dispose();
  21061. index--;
  21062. }
  21063. }
  21064. }
  21065. // facet data
  21066. if (this._facetDataEnabled) {
  21067. this.disableFacetData();
  21068. }
  21069. this.onAfterWorldMatrixUpdateObservable.clear();
  21070. this.onCollideObservable.clear();
  21071. this.onCollisionPositionChangeObservable.clear();
  21072. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21073. };
  21074. /**
  21075. * Adds the passed mesh as a child to the current mesh
  21076. * @param mesh defines the child mesh
  21077. * @returns the current mesh
  21078. */
  21079. AbstractMesh.prototype.addChild = function (mesh) {
  21080. mesh.setParent(this);
  21081. return this;
  21082. };
  21083. /**
  21084. * Removes the passed mesh from the current mesh children list
  21085. * @param mesh defines the child mesh
  21086. * @returns the current mesh
  21087. */
  21088. AbstractMesh.prototype.removeChild = function (mesh) {
  21089. mesh.setParent(null);
  21090. return this;
  21091. };
  21092. // Facet data
  21093. /** @hidden */
  21094. AbstractMesh.prototype._initFacetData = function () {
  21095. if (!this._facetNormals) {
  21096. this._facetNormals = new Array();
  21097. }
  21098. if (!this._facetPositions) {
  21099. this._facetPositions = new Array();
  21100. }
  21101. if (!this._facetPartitioning) {
  21102. this._facetPartitioning = new Array();
  21103. }
  21104. this._facetNb = (this.getIndices().length / 3) | 0;
  21105. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21106. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21107. for (var f = 0; f < this._facetNb; f++) {
  21108. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21109. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21110. }
  21111. this._facetDataEnabled = true;
  21112. return this;
  21113. };
  21114. /**
  21115. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21116. * This method can be called within the render loop.
  21117. * 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
  21118. * @returns the current mesh
  21119. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21120. */
  21121. AbstractMesh.prototype.updateFacetData = function () {
  21122. if (!this._facetDataEnabled) {
  21123. this._initFacetData();
  21124. }
  21125. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21126. var indices = this.getIndices();
  21127. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21128. var bInfo = this.getBoundingInfo();
  21129. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21130. // init arrays, matrix and sort function on first call
  21131. this._facetDepthSortEnabled = true;
  21132. if (indices instanceof Uint16Array) {
  21133. this._depthSortedIndices = new Uint16Array(indices);
  21134. }
  21135. else if (indices instanceof Uint32Array) {
  21136. this._depthSortedIndices = new Uint32Array(indices);
  21137. }
  21138. else {
  21139. var needs32bits = false;
  21140. for (var i = 0; i < indices.length; i++) {
  21141. if (indices[i] > 65535) {
  21142. needs32bits = true;
  21143. break;
  21144. }
  21145. }
  21146. if (needs32bits) {
  21147. this._depthSortedIndices = new Uint32Array(indices);
  21148. }
  21149. else {
  21150. this._depthSortedIndices = new Uint16Array(indices);
  21151. }
  21152. }
  21153. this._facetDepthSortFunction = function (f1, f2) {
  21154. return (f2.sqDistance - f1.sqDistance);
  21155. };
  21156. if (!this._facetDepthSortFrom) {
  21157. var camera = this.getScene().activeCamera;
  21158. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21159. }
  21160. this._depthSortedFacets = [];
  21161. for (var f = 0; f < this._facetNb; f++) {
  21162. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21163. this._depthSortedFacets.push(depthSortedFacet);
  21164. }
  21165. this._invertedMatrix = BABYLON.Matrix.Identity();
  21166. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21167. }
  21168. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21169. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21170. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21171. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21172. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21173. this._subDiv.max = this._partitioningSubdivisions;
  21174. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21175. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21176. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21177. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21178. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21179. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21180. // set the parameters for ComputeNormals()
  21181. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21182. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21183. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21184. this._facetParameters.bInfo = bInfo;
  21185. this._facetParameters.bbSize = this._bbSize;
  21186. this._facetParameters.subDiv = this._subDiv;
  21187. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21188. this._facetParameters.depthSort = this._facetDepthSort;
  21189. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21190. this.computeWorldMatrix(true);
  21191. this._worldMatrix.invertToRef(this._invertedMatrix);
  21192. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21193. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21194. }
  21195. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21196. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21197. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21198. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21199. var l = (this._depthSortedIndices.length / 3) | 0;
  21200. for (var f = 0; f < l; f++) {
  21201. var sind = this._depthSortedFacets[f].ind;
  21202. this._depthSortedIndices[f * 3] = indices[sind];
  21203. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21204. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21205. }
  21206. this.updateIndices(this._depthSortedIndices);
  21207. }
  21208. return this;
  21209. };
  21210. /**
  21211. * Returns the facetLocalNormals array.
  21212. * The normals are expressed in the mesh local spac
  21213. * @returns an array of Vector3
  21214. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21215. */
  21216. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21217. if (!this._facetNormals) {
  21218. this.updateFacetData();
  21219. }
  21220. return this._facetNormals;
  21221. };
  21222. /**
  21223. * Returns the facetLocalPositions array.
  21224. * The facet positions are expressed in the mesh local space
  21225. * @returns an array of Vector3
  21226. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21227. */
  21228. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21229. if (!this._facetPositions) {
  21230. this.updateFacetData();
  21231. }
  21232. return this._facetPositions;
  21233. };
  21234. /**
  21235. * Returns the facetLocalPartioning array
  21236. * @returns an array of array of numbers
  21237. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21238. */
  21239. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21240. if (!this._facetPartitioning) {
  21241. this.updateFacetData();
  21242. }
  21243. return this._facetPartitioning;
  21244. };
  21245. /**
  21246. * Returns the i-th facet position in the world system.
  21247. * This method allocates a new Vector3 per call
  21248. * @param i defines the facet index
  21249. * @returns a new Vector3
  21250. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21251. */
  21252. AbstractMesh.prototype.getFacetPosition = function (i) {
  21253. var pos = BABYLON.Vector3.Zero();
  21254. this.getFacetPositionToRef(i, pos);
  21255. return pos;
  21256. };
  21257. /**
  21258. * Sets the reference Vector3 with the i-th facet position in the world system
  21259. * @param i defines the facet index
  21260. * @param ref defines the target vector
  21261. * @returns the current mesh
  21262. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21263. */
  21264. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21265. var localPos = (this.getFacetLocalPositions())[i];
  21266. var world = this.getWorldMatrix();
  21267. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21268. return this;
  21269. };
  21270. /**
  21271. * Returns the i-th facet normal in the world system.
  21272. * This method allocates a new Vector3 per call
  21273. * @param i defines the facet index
  21274. * @returns a new Vector3
  21275. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21276. */
  21277. AbstractMesh.prototype.getFacetNormal = function (i) {
  21278. var norm = BABYLON.Vector3.Zero();
  21279. this.getFacetNormalToRef(i, norm);
  21280. return norm;
  21281. };
  21282. /**
  21283. * Sets the reference Vector3 with the i-th facet normal in the world system
  21284. * @param i defines the facet index
  21285. * @param ref defines the target vector
  21286. * @returns the current mesh
  21287. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21288. */
  21289. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21290. var localNorm = (this.getFacetLocalNormals())[i];
  21291. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21292. return this;
  21293. };
  21294. /**
  21295. * 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)
  21296. * @param x defines x coordinate
  21297. * @param y defines y coordinate
  21298. * @param z defines z coordinate
  21299. * @returns the array of facet indexes
  21300. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21301. */
  21302. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21303. var bInfo = this.getBoundingInfo();
  21304. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21305. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21306. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21307. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21308. return null;
  21309. }
  21310. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21311. };
  21312. /**
  21313. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21314. * @param projected sets as the (x,y,z) world projection on the facet
  21315. * @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
  21316. * @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
  21317. * @param x defines x coordinate
  21318. * @param y defines y coordinate
  21319. * @param z defines z coordinate
  21320. * @returns the face index if found (or null instead)
  21321. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21322. */
  21323. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21324. if (checkFace === void 0) { checkFace = false; }
  21325. if (facing === void 0) { facing = true; }
  21326. var world = this.getWorldMatrix();
  21327. var invMat = BABYLON.Tmp.Matrix[5];
  21328. world.invertToRef(invMat);
  21329. var invVect = BABYLON.Tmp.Vector3[8];
  21330. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21331. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21332. if (projected) {
  21333. // tranform the local computed projected vector to world coordinates
  21334. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21335. }
  21336. return closest;
  21337. };
  21338. /**
  21339. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21340. * @param projected sets as the (x,y,z) local projection on the facet
  21341. * @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
  21342. * @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
  21343. * @param x defines x coordinate
  21344. * @param y defines y coordinate
  21345. * @param z defines z coordinate
  21346. * @returns the face index if found (or null instead)
  21347. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21348. */
  21349. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21350. if (checkFace === void 0) { checkFace = false; }
  21351. if (facing === void 0) { facing = true; }
  21352. var closest = null;
  21353. var tmpx = 0.0;
  21354. var tmpy = 0.0;
  21355. var tmpz = 0.0;
  21356. var d = 0.0; // tmp dot facet normal * facet position
  21357. var t0 = 0.0;
  21358. var projx = 0.0;
  21359. var projy = 0.0;
  21360. var projz = 0.0;
  21361. // Get all the facets in the same partitioning block than (x, y, z)
  21362. var facetPositions = this.getFacetLocalPositions();
  21363. var facetNormals = this.getFacetLocalNormals();
  21364. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21365. if (!facetsInBlock) {
  21366. return null;
  21367. }
  21368. // Get the closest facet to (x, y, z)
  21369. var shortest = Number.MAX_VALUE; // init distance vars
  21370. var tmpDistance = shortest;
  21371. var fib; // current facet in the block
  21372. var norm; // current facet normal
  21373. var p0; // current facet barycenter position
  21374. // loop on all the facets in the current partitioning block
  21375. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21376. fib = facetsInBlock[idx];
  21377. norm = facetNormals[fib];
  21378. p0 = facetPositions[fib];
  21379. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21380. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21381. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21382. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21383. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21384. projx = x + norm.x * t0;
  21385. projy = y + norm.y * t0;
  21386. projz = z + norm.z * t0;
  21387. tmpx = projx - x;
  21388. tmpy = projy - y;
  21389. tmpz = projz - z;
  21390. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21391. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21392. shortest = tmpDistance;
  21393. closest = fib;
  21394. if (projected) {
  21395. projected.x = projx;
  21396. projected.y = projy;
  21397. projected.z = projz;
  21398. }
  21399. }
  21400. }
  21401. }
  21402. return closest;
  21403. };
  21404. /**
  21405. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21406. * @returns the parameters
  21407. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21408. */
  21409. AbstractMesh.prototype.getFacetDataParameters = function () {
  21410. return this._facetParameters;
  21411. };
  21412. /**
  21413. * Disables the feature FacetData and frees the related memory
  21414. * @returns the current mesh
  21415. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21416. */
  21417. AbstractMesh.prototype.disableFacetData = function () {
  21418. if (this._facetDataEnabled) {
  21419. this._facetDataEnabled = false;
  21420. this._facetPositions = new Array();
  21421. this._facetNormals = new Array();
  21422. this._facetPartitioning = new Array();
  21423. this._facetParameters = null;
  21424. this._depthSortedIndices = new Uint32Array(0);
  21425. }
  21426. return this;
  21427. };
  21428. /**
  21429. * Updates the AbstractMesh indices array
  21430. * @param indices defines the data source
  21431. * @returns the current mesh
  21432. */
  21433. AbstractMesh.prototype.updateIndices = function (indices) {
  21434. return this;
  21435. };
  21436. /**
  21437. * Creates new normals data for the mesh
  21438. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21439. * @returns the current mesh
  21440. */
  21441. AbstractMesh.prototype.createNormals = function (updatable) {
  21442. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21443. var indices = this.getIndices();
  21444. var normals;
  21445. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21446. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21447. }
  21448. else {
  21449. normals = [];
  21450. }
  21451. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21452. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21453. return this;
  21454. };
  21455. /**
  21456. * Align the mesh with a normal
  21457. * @param normal defines the normal to use
  21458. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21459. * @returns the current mesh
  21460. */
  21461. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21462. if (!upDirection) {
  21463. upDirection = BABYLON.Axis.Y;
  21464. }
  21465. var axisX = BABYLON.Tmp.Vector3[0];
  21466. var axisZ = BABYLON.Tmp.Vector3[1];
  21467. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21468. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21469. if (this.rotationQuaternion) {
  21470. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21471. }
  21472. else {
  21473. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21474. }
  21475. return this;
  21476. };
  21477. /** @hidden */
  21478. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21479. var engine = this.getEngine();
  21480. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21481. this._isOccluded = false;
  21482. return;
  21483. }
  21484. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21485. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21486. if (isOcclusionQueryAvailable) {
  21487. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21488. this._isOcclusionQueryInProgress = false;
  21489. this._occlusionInternalRetryCounter = 0;
  21490. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21491. }
  21492. else {
  21493. this._occlusionInternalRetryCounter++;
  21494. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21495. this._isOcclusionQueryInProgress = false;
  21496. this._occlusionInternalRetryCounter = 0;
  21497. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21498. // if strict continue the last state of the object.
  21499. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21500. }
  21501. else {
  21502. return;
  21503. }
  21504. }
  21505. }
  21506. var scene = this.getScene();
  21507. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21508. if (!this._occlusionQuery) {
  21509. this._occlusionQuery = engine.createQuery();
  21510. }
  21511. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21512. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21513. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21514. this._isOcclusionQueryInProgress = true;
  21515. };
  21516. /** No occlusion */
  21517. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21518. /** Occlusion set to optimisitic */
  21519. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21520. /** Occlusion set to strict */
  21521. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21522. /** Use an accurante occlusion algorithm */
  21523. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21524. /** Use a conservative occlusion algorithm */
  21525. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21526. return AbstractMesh;
  21527. }(BABYLON.TransformNode));
  21528. BABYLON.AbstractMesh = AbstractMesh;
  21529. })(BABYLON || (BABYLON = {}));
  21530. //# sourceMappingURL=babylon.abstractMesh.js.map
  21531. var BABYLON;
  21532. (function (BABYLON) {
  21533. /**
  21534. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21535. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21536. * 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.
  21537. */
  21538. var Light = /** @class */ (function (_super) {
  21539. __extends(Light, _super);
  21540. /**
  21541. * Creates a Light object in the scene.
  21542. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21543. * @param name The firendly name of the light
  21544. * @param scene The scene the light belongs too
  21545. */
  21546. function Light(name, scene) {
  21547. var _this = _super.call(this, name, scene) || this;
  21548. /**
  21549. * Diffuse gives the basic color to an object.
  21550. */
  21551. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21552. /**
  21553. * Specular produces a highlight color on an object.
  21554. * Note: This is note affecting PBR materials.
  21555. */
  21556. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21557. /**
  21558. * Strength of the light.
  21559. * Note: By default it is define in the framework own unit.
  21560. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21561. */
  21562. _this.intensity = 1.0;
  21563. /**
  21564. * Defines how far from the source the light is impacting in scene units.
  21565. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21566. */
  21567. _this.range = Number.MAX_VALUE;
  21568. /**
  21569. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21570. * of light.
  21571. */
  21572. _this._photometricScale = 1.0;
  21573. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21574. _this._radius = 0.00001;
  21575. /**
  21576. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21577. * exceeding the number allowed of the materials.
  21578. */
  21579. _this.renderPriority = 0;
  21580. _this._shadowEnabled = true;
  21581. _this._excludeWithLayerMask = 0;
  21582. _this._includeOnlyWithLayerMask = 0;
  21583. _this._lightmapMode = 0;
  21584. /**
  21585. * @hidden Internal use only.
  21586. */
  21587. _this._excludedMeshesIds = new Array();
  21588. /**
  21589. * @hidden Internal use only.
  21590. */
  21591. _this._includedOnlyMeshesIds = new Array();
  21592. _this.getScene().addLight(_this);
  21593. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21594. _this._buildUniformLayout();
  21595. _this.includedOnlyMeshes = new Array();
  21596. _this.excludedMeshes = new Array();
  21597. _this._resyncMeshes();
  21598. return _this;
  21599. }
  21600. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21601. /**
  21602. * If every light affecting the material is in this lightmapMode,
  21603. * material.lightmapTexture adds or multiplies
  21604. * (depends on material.useLightmapAsShadowmap)
  21605. * after every other light calculations.
  21606. */
  21607. get: function () {
  21608. return Light._LIGHTMAP_DEFAULT;
  21609. },
  21610. enumerable: true,
  21611. configurable: true
  21612. });
  21613. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21614. /**
  21615. * material.lightmapTexture as only diffuse lighting from this light
  21616. * adds only specular lighting from this light
  21617. * adds dynamic shadows
  21618. */
  21619. get: function () {
  21620. return Light._LIGHTMAP_SPECULAR;
  21621. },
  21622. enumerable: true,
  21623. configurable: true
  21624. });
  21625. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21626. /**
  21627. * material.lightmapTexture as only lighting
  21628. * no light calculation from this light
  21629. * only adds dynamic shadows from this light
  21630. */
  21631. get: function () {
  21632. return Light._LIGHTMAP_SHADOWSONLY;
  21633. },
  21634. enumerable: true,
  21635. configurable: true
  21636. });
  21637. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21638. /**
  21639. * Each light type uses the default quantity according to its type:
  21640. * point/spot lights use luminous intensity
  21641. * directional lights use illuminance
  21642. */
  21643. get: function () {
  21644. return Light._INTENSITYMODE_AUTOMATIC;
  21645. },
  21646. enumerable: true,
  21647. configurable: true
  21648. });
  21649. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21650. /**
  21651. * lumen (lm)
  21652. */
  21653. get: function () {
  21654. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21655. },
  21656. enumerable: true,
  21657. configurable: true
  21658. });
  21659. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21660. /**
  21661. * candela (lm/sr)
  21662. */
  21663. get: function () {
  21664. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21665. },
  21666. enumerable: true,
  21667. configurable: true
  21668. });
  21669. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21670. /**
  21671. * lux (lm/m^2)
  21672. */
  21673. get: function () {
  21674. return Light._INTENSITYMODE_ILLUMINANCE;
  21675. },
  21676. enumerable: true,
  21677. configurable: true
  21678. });
  21679. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21680. /**
  21681. * nit (cd/m^2)
  21682. */
  21683. get: function () {
  21684. return Light._INTENSITYMODE_LUMINANCE;
  21685. },
  21686. enumerable: true,
  21687. configurable: true
  21688. });
  21689. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21690. /**
  21691. * Light type const id of the point light.
  21692. */
  21693. get: function () {
  21694. return Light._LIGHTTYPEID_POINTLIGHT;
  21695. },
  21696. enumerable: true,
  21697. configurable: true
  21698. });
  21699. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21700. /**
  21701. * Light type const id of the directional light.
  21702. */
  21703. get: function () {
  21704. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21705. },
  21706. enumerable: true,
  21707. configurable: true
  21708. });
  21709. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21710. /**
  21711. * Light type const id of the spot light.
  21712. */
  21713. get: function () {
  21714. return Light._LIGHTTYPEID_SPOTLIGHT;
  21715. },
  21716. enumerable: true,
  21717. configurable: true
  21718. });
  21719. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21720. /**
  21721. * Light type const id of the hemispheric light.
  21722. */
  21723. get: function () {
  21724. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21725. },
  21726. enumerable: true,
  21727. configurable: true
  21728. });
  21729. Object.defineProperty(Light.prototype, "intensityMode", {
  21730. /**
  21731. * Gets the photometric scale used to interpret the intensity.
  21732. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21733. */
  21734. get: function () {
  21735. return this._intensityMode;
  21736. },
  21737. /**
  21738. * Sets the photometric scale used to interpret the intensity.
  21739. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21740. */
  21741. set: function (value) {
  21742. this._intensityMode = value;
  21743. this._computePhotometricScale();
  21744. },
  21745. enumerable: true,
  21746. configurable: true
  21747. });
  21748. ;
  21749. ;
  21750. Object.defineProperty(Light.prototype, "radius", {
  21751. /**
  21752. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21753. */
  21754. get: function () {
  21755. return this._radius;
  21756. },
  21757. /**
  21758. * sets the light radius used by PBR Materials to simulate soft area lights.
  21759. */
  21760. set: function (value) {
  21761. this._radius = value;
  21762. this._computePhotometricScale();
  21763. },
  21764. enumerable: true,
  21765. configurable: true
  21766. });
  21767. ;
  21768. ;
  21769. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21770. /**
  21771. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21772. * the current shadow generator.
  21773. */
  21774. get: function () {
  21775. return this._shadowEnabled;
  21776. },
  21777. /**
  21778. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21779. * the current shadow generator.
  21780. */
  21781. set: function (value) {
  21782. if (this._shadowEnabled === value) {
  21783. return;
  21784. }
  21785. this._shadowEnabled = value;
  21786. this._markMeshesAsLightDirty();
  21787. },
  21788. enumerable: true,
  21789. configurable: true
  21790. });
  21791. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21792. /**
  21793. * Gets the only meshes impacted by this light.
  21794. */
  21795. get: function () {
  21796. return this._includedOnlyMeshes;
  21797. },
  21798. /**
  21799. * Sets the only meshes impacted by this light.
  21800. */
  21801. set: function (value) {
  21802. this._includedOnlyMeshes = value;
  21803. this._hookArrayForIncludedOnly(value);
  21804. },
  21805. enumerable: true,
  21806. configurable: true
  21807. });
  21808. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21809. /**
  21810. * Gets the meshes not impacted by this light.
  21811. */
  21812. get: function () {
  21813. return this._excludedMeshes;
  21814. },
  21815. /**
  21816. * Sets the meshes not impacted by this light.
  21817. */
  21818. set: function (value) {
  21819. this._excludedMeshes = value;
  21820. this._hookArrayForExcluded(value);
  21821. },
  21822. enumerable: true,
  21823. configurable: true
  21824. });
  21825. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21826. /**
  21827. * Gets the layer id use to find what meshes are not impacted by the light.
  21828. * Inactive if 0
  21829. */
  21830. get: function () {
  21831. return this._excludeWithLayerMask;
  21832. },
  21833. /**
  21834. * Sets the layer id use to find what meshes are not impacted by the light.
  21835. * Inactive if 0
  21836. */
  21837. set: function (value) {
  21838. this._excludeWithLayerMask = value;
  21839. this._resyncMeshes();
  21840. },
  21841. enumerable: true,
  21842. configurable: true
  21843. });
  21844. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21845. /**
  21846. * Gets the layer id use to find what meshes are impacted by the light.
  21847. * Inactive if 0
  21848. */
  21849. get: function () {
  21850. return this._includeOnlyWithLayerMask;
  21851. },
  21852. /**
  21853. * Sets the layer id use to find what meshes are impacted by the light.
  21854. * Inactive if 0
  21855. */
  21856. set: function (value) {
  21857. this._includeOnlyWithLayerMask = value;
  21858. this._resyncMeshes();
  21859. },
  21860. enumerable: true,
  21861. configurable: true
  21862. });
  21863. Object.defineProperty(Light.prototype, "lightmapMode", {
  21864. /**
  21865. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21866. */
  21867. get: function () {
  21868. return this._lightmapMode;
  21869. },
  21870. /**
  21871. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21872. */
  21873. set: function (value) {
  21874. if (this._lightmapMode === value) {
  21875. return;
  21876. }
  21877. this._lightmapMode = value;
  21878. this._markMeshesAsLightDirty();
  21879. },
  21880. enumerable: true,
  21881. configurable: true
  21882. });
  21883. /**
  21884. * Returns the string "Light".
  21885. * @returns the class name
  21886. */
  21887. Light.prototype.getClassName = function () {
  21888. return "Light";
  21889. };
  21890. /**
  21891. * Converts the light information to a readable string for debug purpose.
  21892. * @param fullDetails Supports for multiple levels of logging within scene loading
  21893. * @returns the human readable light info
  21894. */
  21895. Light.prototype.toString = function (fullDetails) {
  21896. var ret = "Name: " + this.name;
  21897. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21898. if (this.animations) {
  21899. for (var i = 0; i < this.animations.length; i++) {
  21900. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21901. }
  21902. }
  21903. if (fullDetails) {
  21904. }
  21905. return ret;
  21906. };
  21907. /**
  21908. * Set the enabled state of this node.
  21909. * @param value - the new enabled state
  21910. */
  21911. Light.prototype.setEnabled = function (value) {
  21912. _super.prototype.setEnabled.call(this, value);
  21913. this._resyncMeshes();
  21914. };
  21915. /**
  21916. * Returns the Light associated shadow generator if any.
  21917. * @return the associated shadow generator.
  21918. */
  21919. Light.prototype.getShadowGenerator = function () {
  21920. return this._shadowGenerator;
  21921. };
  21922. /**
  21923. * Returns a Vector3, the absolute light position in the World.
  21924. * @returns the world space position of the light
  21925. */
  21926. Light.prototype.getAbsolutePosition = function () {
  21927. return BABYLON.Vector3.Zero();
  21928. };
  21929. /**
  21930. * Specifies if the light will affect the passed mesh.
  21931. * @param mesh The mesh to test against the light
  21932. * @return true the mesh is affected otherwise, false.
  21933. */
  21934. Light.prototype.canAffectMesh = function (mesh) {
  21935. if (!mesh) {
  21936. return true;
  21937. }
  21938. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21939. return false;
  21940. }
  21941. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21942. return false;
  21943. }
  21944. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21945. return false;
  21946. }
  21947. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21948. return false;
  21949. }
  21950. return true;
  21951. };
  21952. /**
  21953. * Computes and Returns the light World matrix.
  21954. * @returns the world matrix
  21955. */
  21956. Light.prototype.getWorldMatrix = function () {
  21957. this._currentRenderId = this.getScene().getRenderId();
  21958. this._childRenderId = this._currentRenderId;
  21959. var worldMatrix = this._getWorldMatrix();
  21960. if (this.parent && this.parent.getWorldMatrix) {
  21961. if (!this._parentedWorldMatrix) {
  21962. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21963. }
  21964. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21965. this._markSyncedWithParent();
  21966. return this._parentedWorldMatrix;
  21967. }
  21968. return worldMatrix;
  21969. };
  21970. /**
  21971. * Sort function to order lights for rendering.
  21972. * @param a First Light object to compare to second.
  21973. * @param b Second Light object to compare first.
  21974. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21975. */
  21976. Light.CompareLightsPriority = function (a, b) {
  21977. //shadow-casting lights have priority over non-shadow-casting lights
  21978. //the renderPrioirty is a secondary sort criterion
  21979. if (a.shadowEnabled !== b.shadowEnabled) {
  21980. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21981. }
  21982. return b.renderPriority - a.renderPriority;
  21983. };
  21984. /**
  21985. * Releases resources associated with this node.
  21986. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21987. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21988. */
  21989. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21990. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21991. if (this._shadowGenerator) {
  21992. this._shadowGenerator.dispose();
  21993. this._shadowGenerator = null;
  21994. }
  21995. // Animations
  21996. this.getScene().stopAnimation(this);
  21997. // Remove from meshes
  21998. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21999. var mesh = _a[_i];
  22000. mesh._removeLightSource(this);
  22001. }
  22002. this._uniformBuffer.dispose();
  22003. // Remove from scene
  22004. this.getScene().removeLight(this);
  22005. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22006. };
  22007. /**
  22008. * Returns the light type ID (integer).
  22009. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22010. */
  22011. Light.prototype.getTypeID = function () {
  22012. return 0;
  22013. };
  22014. /**
  22015. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22016. * @returns the scaled intensity in intensity mode unit
  22017. */
  22018. Light.prototype.getScaledIntensity = function () {
  22019. return this._photometricScale * this.intensity;
  22020. };
  22021. /**
  22022. * Returns a new Light object, named "name", from the current one.
  22023. * @param name The name of the cloned light
  22024. * @returns the new created light
  22025. */
  22026. Light.prototype.clone = function (name) {
  22027. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22028. if (!constructor) {
  22029. return null;
  22030. }
  22031. return BABYLON.SerializationHelper.Clone(constructor, this);
  22032. };
  22033. /**
  22034. * Serializes the current light into a Serialization object.
  22035. * @returns the serialized object.
  22036. */
  22037. Light.prototype.serialize = function () {
  22038. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22039. // Type
  22040. serializationObject.type = this.getTypeID();
  22041. // Parent
  22042. if (this.parent) {
  22043. serializationObject.parentId = this.parent.id;
  22044. }
  22045. // Inclusion / exclusions
  22046. if (this.excludedMeshes.length > 0) {
  22047. serializationObject.excludedMeshesIds = [];
  22048. this.excludedMeshes.forEach(function (mesh) {
  22049. serializationObject.excludedMeshesIds.push(mesh.id);
  22050. });
  22051. }
  22052. if (this.includedOnlyMeshes.length > 0) {
  22053. serializationObject.includedOnlyMeshesIds = [];
  22054. this.includedOnlyMeshes.forEach(function (mesh) {
  22055. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22056. });
  22057. }
  22058. // Animations
  22059. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22060. serializationObject.ranges = this.serializeAnimationRanges();
  22061. return serializationObject;
  22062. };
  22063. /**
  22064. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22065. * This new light is named "name" and added to the passed scene.
  22066. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22067. * @param name The friendly name of the light
  22068. * @param scene The scene the new light will belong to
  22069. * @returns the constructor function
  22070. */
  22071. Light.GetConstructorFromName = function (type, name, scene) {
  22072. switch (type) {
  22073. case 0:
  22074. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22075. case 1:
  22076. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22077. case 2:
  22078. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22079. case 3:
  22080. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22081. }
  22082. return null;
  22083. };
  22084. /**
  22085. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22086. * @param parsedLight The JSON representation of the light
  22087. * @param scene The scene to create the parsed light in
  22088. * @returns the created light after parsing
  22089. */
  22090. Light.Parse = function (parsedLight, scene) {
  22091. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22092. if (!constructor) {
  22093. return null;
  22094. }
  22095. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22096. // Inclusion / exclusions
  22097. if (parsedLight.excludedMeshesIds) {
  22098. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22099. }
  22100. if (parsedLight.includedOnlyMeshesIds) {
  22101. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22102. }
  22103. // Parent
  22104. if (parsedLight.parentId) {
  22105. light._waitingParentId = parsedLight.parentId;
  22106. }
  22107. // Animations
  22108. if (parsedLight.animations) {
  22109. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22110. var parsedAnimation = parsedLight.animations[animationIndex];
  22111. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22112. }
  22113. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22114. }
  22115. if (parsedLight.autoAnimate) {
  22116. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22117. }
  22118. return light;
  22119. };
  22120. Light.prototype._hookArrayForExcluded = function (array) {
  22121. var _this = this;
  22122. var oldPush = array.push;
  22123. array.push = function () {
  22124. var items = [];
  22125. for (var _i = 0; _i < arguments.length; _i++) {
  22126. items[_i] = arguments[_i];
  22127. }
  22128. var result = oldPush.apply(array, items);
  22129. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22130. var item = items_1[_a];
  22131. item._resyncLighSource(_this);
  22132. }
  22133. return result;
  22134. };
  22135. var oldSplice = array.splice;
  22136. array.splice = function (index, deleteCount) {
  22137. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22138. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22139. var item = deleted_1[_i];
  22140. item._resyncLighSource(_this);
  22141. }
  22142. return deleted;
  22143. };
  22144. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22145. var item = array_1[_i];
  22146. item._resyncLighSource(this);
  22147. }
  22148. };
  22149. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22150. var _this = this;
  22151. var oldPush = array.push;
  22152. array.push = function () {
  22153. var items = [];
  22154. for (var _i = 0; _i < arguments.length; _i++) {
  22155. items[_i] = arguments[_i];
  22156. }
  22157. var result = oldPush.apply(array, items);
  22158. _this._resyncMeshes();
  22159. return result;
  22160. };
  22161. var oldSplice = array.splice;
  22162. array.splice = function (index, deleteCount) {
  22163. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22164. _this._resyncMeshes();
  22165. return deleted;
  22166. };
  22167. this._resyncMeshes();
  22168. };
  22169. Light.prototype._resyncMeshes = function () {
  22170. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22171. var mesh = _a[_i];
  22172. mesh._resyncLighSource(this);
  22173. }
  22174. };
  22175. /**
  22176. * Forces the meshes to update their light related information in their rendering used effects
  22177. * @hidden Internal Use Only
  22178. */
  22179. Light.prototype._markMeshesAsLightDirty = function () {
  22180. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22181. var mesh = _a[_i];
  22182. if (mesh._lightSources.indexOf(this) !== -1) {
  22183. mesh._markSubMeshesAsLightDirty();
  22184. }
  22185. }
  22186. };
  22187. /**
  22188. * Recomputes the cached photometric scale if needed.
  22189. */
  22190. Light.prototype._computePhotometricScale = function () {
  22191. this._photometricScale = this._getPhotometricScale();
  22192. this.getScene().resetCachedMaterial();
  22193. };
  22194. /**
  22195. * Returns the Photometric Scale according to the light type and intensity mode.
  22196. */
  22197. Light.prototype._getPhotometricScale = function () {
  22198. var photometricScale = 0.0;
  22199. var lightTypeID = this.getTypeID();
  22200. //get photometric mode
  22201. var photometricMode = this.intensityMode;
  22202. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22203. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22204. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22205. }
  22206. else {
  22207. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22208. }
  22209. }
  22210. //compute photometric scale
  22211. switch (lightTypeID) {
  22212. case Light.LIGHTTYPEID_POINTLIGHT:
  22213. case Light.LIGHTTYPEID_SPOTLIGHT:
  22214. switch (photometricMode) {
  22215. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22216. photometricScale = 1.0 / (4.0 * Math.PI);
  22217. break;
  22218. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22219. photometricScale = 1.0;
  22220. break;
  22221. case Light.INTENSITYMODE_LUMINANCE:
  22222. photometricScale = this.radius * this.radius;
  22223. break;
  22224. }
  22225. break;
  22226. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22227. switch (photometricMode) {
  22228. case Light.INTENSITYMODE_ILLUMINANCE:
  22229. photometricScale = 1.0;
  22230. break;
  22231. case Light.INTENSITYMODE_LUMINANCE:
  22232. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22233. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22234. var apexAngleRadians = this.radius;
  22235. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22236. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22237. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22238. photometricScale = solidAngle;
  22239. break;
  22240. }
  22241. break;
  22242. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22243. // No fall off in hemisperic light.
  22244. photometricScale = 1.0;
  22245. break;
  22246. }
  22247. return photometricScale;
  22248. };
  22249. /**
  22250. * Reorder the light in the scene according to their defined priority.
  22251. * @hidden Internal Use Only
  22252. */
  22253. Light.prototype._reorderLightsInScene = function () {
  22254. var scene = this.getScene();
  22255. if (this._renderPriority != 0) {
  22256. scene.requireLightSorting = true;
  22257. }
  22258. this.getScene().sortLightsByPriority();
  22259. };
  22260. //lightmapMode Consts
  22261. Light._LIGHTMAP_DEFAULT = 0;
  22262. Light._LIGHTMAP_SPECULAR = 1;
  22263. Light._LIGHTMAP_SHADOWSONLY = 2;
  22264. // Intensity Mode Consts
  22265. Light._INTENSITYMODE_AUTOMATIC = 0;
  22266. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22267. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22268. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22269. Light._INTENSITYMODE_LUMINANCE = 4;
  22270. // Light types ids const.
  22271. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22272. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22273. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22274. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22275. __decorate([
  22276. BABYLON.serializeAsColor3()
  22277. ], Light.prototype, "diffuse", void 0);
  22278. __decorate([
  22279. BABYLON.serializeAsColor3()
  22280. ], Light.prototype, "specular", void 0);
  22281. __decorate([
  22282. BABYLON.serialize()
  22283. ], Light.prototype, "intensity", void 0);
  22284. __decorate([
  22285. BABYLON.serialize()
  22286. ], Light.prototype, "range", void 0);
  22287. __decorate([
  22288. BABYLON.serialize()
  22289. ], Light.prototype, "intensityMode", null);
  22290. __decorate([
  22291. BABYLON.serialize()
  22292. ], Light.prototype, "radius", null);
  22293. __decorate([
  22294. BABYLON.serialize()
  22295. ], Light.prototype, "_renderPriority", void 0);
  22296. __decorate([
  22297. BABYLON.expandToProperty("_reorderLightsInScene")
  22298. ], Light.prototype, "renderPriority", void 0);
  22299. __decorate([
  22300. BABYLON.serialize("shadowEnabled")
  22301. ], Light.prototype, "_shadowEnabled", void 0);
  22302. __decorate([
  22303. BABYLON.serialize("excludeWithLayerMask")
  22304. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22305. __decorate([
  22306. BABYLON.serialize("includeOnlyWithLayerMask")
  22307. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22308. __decorate([
  22309. BABYLON.serialize("lightmapMode")
  22310. ], Light.prototype, "_lightmapMode", void 0);
  22311. return Light;
  22312. }(BABYLON.Node));
  22313. BABYLON.Light = Light;
  22314. })(BABYLON || (BABYLON = {}));
  22315. //# sourceMappingURL=babylon.light.js.map
  22316. var BABYLON;
  22317. (function (BABYLON) {
  22318. var Camera = /** @class */ (function (_super) {
  22319. __extends(Camera, _super);
  22320. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22321. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22322. var _this = _super.call(this, name, scene) || this;
  22323. /**
  22324. * The vector the camera should consider as up.
  22325. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22326. */
  22327. _this.upVector = BABYLON.Vector3.Up();
  22328. _this.orthoLeft = null;
  22329. _this.orthoRight = null;
  22330. _this.orthoBottom = null;
  22331. _this.orthoTop = null;
  22332. /**
  22333. * FOV is set in Radians. (default is 0.8)
  22334. */
  22335. _this.fov = 0.8;
  22336. _this.minZ = 1;
  22337. _this.maxZ = 10000.0;
  22338. _this.inertia = 0.9;
  22339. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22340. _this.isIntermediate = false;
  22341. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22342. /**
  22343. * Restricts the camera to viewing objects with the same layerMask.
  22344. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22345. */
  22346. _this.layerMask = 0x0FFFFFFF;
  22347. /**
  22348. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22349. */
  22350. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22351. // Camera rig members
  22352. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22353. _this._rigCameras = new Array();
  22354. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22355. _this._skipRendering = false;
  22356. _this.customRenderTargets = new Array();
  22357. // Observables
  22358. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22359. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22360. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22361. _this.onRestoreStateObservable = new BABYLON.Observable();
  22362. // Cache
  22363. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22364. _this._projectionMatrix = new BABYLON.Matrix();
  22365. _this._doNotComputeProjectionMatrix = false;
  22366. _this._worldMatrix = BABYLON.Matrix.Identity();
  22367. _this._postProcesses = new Array();
  22368. _this._transformMatrix = BABYLON.Matrix.Zero();
  22369. _this._activeMeshes = new BABYLON.SmartArray(256);
  22370. _this._globalPosition = BABYLON.Vector3.Zero();
  22371. _this._refreshFrustumPlanes = true;
  22372. _this.getScene().addCamera(_this);
  22373. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22374. _this.getScene().activeCamera = _this;
  22375. }
  22376. _this.position = position;
  22377. return _this;
  22378. }
  22379. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22380. get: function () {
  22381. return Camera._PERSPECTIVE_CAMERA;
  22382. },
  22383. enumerable: true,
  22384. configurable: true
  22385. });
  22386. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22387. get: function () {
  22388. return Camera._ORTHOGRAPHIC_CAMERA;
  22389. },
  22390. enumerable: true,
  22391. configurable: true
  22392. });
  22393. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22394. /**
  22395. * This is the default FOV mode for perspective cameras.
  22396. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22397. *
  22398. */
  22399. get: function () {
  22400. return Camera._FOVMODE_VERTICAL_FIXED;
  22401. },
  22402. enumerable: true,
  22403. configurable: true
  22404. });
  22405. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22406. /**
  22407. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22408. *
  22409. */
  22410. get: function () {
  22411. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22412. },
  22413. enumerable: true,
  22414. configurable: true
  22415. });
  22416. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22417. get: function () {
  22418. return Camera._RIG_MODE_NONE;
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22424. get: function () {
  22425. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22426. },
  22427. enumerable: true,
  22428. configurable: true
  22429. });
  22430. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22431. get: function () {
  22432. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22433. },
  22434. enumerable: true,
  22435. configurable: true
  22436. });
  22437. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22438. get: function () {
  22439. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22445. get: function () {
  22446. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22447. },
  22448. enumerable: true,
  22449. configurable: true
  22450. });
  22451. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22452. get: function () {
  22453. return Camera._RIG_MODE_VR;
  22454. },
  22455. enumerable: true,
  22456. configurable: true
  22457. });
  22458. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22459. get: function () {
  22460. return Camera._RIG_MODE_WEBVR;
  22461. },
  22462. enumerable: true,
  22463. configurable: true
  22464. });
  22465. /**
  22466. * Store current camera state (fov, position, etc..)
  22467. */
  22468. Camera.prototype.storeState = function () {
  22469. this._stateStored = true;
  22470. this._storedFov = this.fov;
  22471. return this;
  22472. };
  22473. /**
  22474. * Restores the camera state values if it has been stored. You must call storeState() first
  22475. */
  22476. Camera.prototype._restoreStateValues = function () {
  22477. if (!this._stateStored) {
  22478. return false;
  22479. }
  22480. this.fov = this._storedFov;
  22481. return true;
  22482. };
  22483. /**
  22484. * Restored camera state. You must call storeState() first
  22485. */
  22486. Camera.prototype.restoreState = function () {
  22487. if (this._restoreStateValues()) {
  22488. this.onRestoreStateObservable.notifyObservers(this);
  22489. return true;
  22490. }
  22491. return false;
  22492. };
  22493. Camera.prototype.getClassName = function () {
  22494. return "Camera";
  22495. };
  22496. /**
  22497. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22498. */
  22499. Camera.prototype.toString = function (fullDetails) {
  22500. var ret = "Name: " + this.name;
  22501. ret += ", type: " + this.getClassName();
  22502. if (this.animations) {
  22503. for (var i = 0; i < this.animations.length; i++) {
  22504. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22505. }
  22506. }
  22507. if (fullDetails) {
  22508. }
  22509. return ret;
  22510. };
  22511. Object.defineProperty(Camera.prototype, "globalPosition", {
  22512. get: function () {
  22513. return this._globalPosition;
  22514. },
  22515. enumerable: true,
  22516. configurable: true
  22517. });
  22518. Camera.prototype.getActiveMeshes = function () {
  22519. return this._activeMeshes;
  22520. };
  22521. Camera.prototype.isActiveMesh = function (mesh) {
  22522. return (this._activeMeshes.indexOf(mesh) !== -1);
  22523. };
  22524. /**
  22525. * Is this camera ready to be used/rendered
  22526. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22527. * @return true if the camera is ready
  22528. */
  22529. Camera.prototype.isReady = function (completeCheck) {
  22530. if (completeCheck === void 0) { completeCheck = false; }
  22531. if (completeCheck) {
  22532. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22533. var pp = _a[_i];
  22534. if (pp && !pp.isReady()) {
  22535. return false;
  22536. }
  22537. }
  22538. }
  22539. return _super.prototype.isReady.call(this, completeCheck);
  22540. };
  22541. //Cache
  22542. Camera.prototype._initCache = function () {
  22543. _super.prototype._initCache.call(this);
  22544. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22545. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22546. this._cache.mode = undefined;
  22547. this._cache.minZ = undefined;
  22548. this._cache.maxZ = undefined;
  22549. this._cache.fov = undefined;
  22550. this._cache.fovMode = undefined;
  22551. this._cache.aspectRatio = undefined;
  22552. this._cache.orthoLeft = undefined;
  22553. this._cache.orthoRight = undefined;
  22554. this._cache.orthoBottom = undefined;
  22555. this._cache.orthoTop = undefined;
  22556. this._cache.renderWidth = undefined;
  22557. this._cache.renderHeight = undefined;
  22558. };
  22559. Camera.prototype._updateCache = function (ignoreParentClass) {
  22560. if (!ignoreParentClass) {
  22561. _super.prototype._updateCache.call(this);
  22562. }
  22563. this._cache.position.copyFrom(this.position);
  22564. this._cache.upVector.copyFrom(this.upVector);
  22565. };
  22566. // Synchronized
  22567. Camera.prototype._isSynchronized = function () {
  22568. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22569. };
  22570. Camera.prototype._isSynchronizedViewMatrix = function () {
  22571. if (!_super.prototype._isSynchronized.call(this))
  22572. return false;
  22573. return this._cache.position.equals(this.position)
  22574. && this._cache.upVector.equals(this.upVector)
  22575. && this.isSynchronizedWithParent();
  22576. };
  22577. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22578. var check = this._cache.mode === this.mode
  22579. && this._cache.minZ === this.minZ
  22580. && this._cache.maxZ === this.maxZ;
  22581. if (!check) {
  22582. return false;
  22583. }
  22584. var engine = this.getEngine();
  22585. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22586. check = this._cache.fov === this.fov
  22587. && this._cache.fovMode === this.fovMode
  22588. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22589. }
  22590. else {
  22591. check = this._cache.orthoLeft === this.orthoLeft
  22592. && this._cache.orthoRight === this.orthoRight
  22593. && this._cache.orthoBottom === this.orthoBottom
  22594. && this._cache.orthoTop === this.orthoTop
  22595. && this._cache.renderWidth === engine.getRenderWidth()
  22596. && this._cache.renderHeight === engine.getRenderHeight();
  22597. }
  22598. return check;
  22599. };
  22600. // Controls
  22601. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22602. };
  22603. Camera.prototype.detachControl = function (element) {
  22604. };
  22605. Camera.prototype.update = function () {
  22606. this._checkInputs();
  22607. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22608. this._updateRigCameras();
  22609. }
  22610. };
  22611. Camera.prototype._checkInputs = function () {
  22612. this.onAfterCheckInputsObservable.notifyObservers(this);
  22613. };
  22614. Object.defineProperty(Camera.prototype, "rigCameras", {
  22615. get: function () {
  22616. return this._rigCameras;
  22617. },
  22618. enumerable: true,
  22619. configurable: true
  22620. });
  22621. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22622. get: function () {
  22623. return this._rigPostProcess;
  22624. },
  22625. enumerable: true,
  22626. configurable: true
  22627. });
  22628. /**
  22629. * Internal, gets the first post proces.
  22630. * @returns the first post process to be run on this camera.
  22631. */
  22632. Camera.prototype._getFirstPostProcess = function () {
  22633. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22634. if (this._postProcesses[ppIndex] !== null) {
  22635. return this._postProcesses[ppIndex];
  22636. }
  22637. }
  22638. return null;
  22639. };
  22640. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22641. // invalidate framebuffer
  22642. var firstPostProcess = this._getFirstPostProcess();
  22643. if (firstPostProcess) {
  22644. firstPostProcess.markTextureDirty();
  22645. }
  22646. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22647. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22648. var cam = this._rigCameras[i];
  22649. var rigPostProcess = cam._rigPostProcess;
  22650. // for VR rig, there does not have to be a post process
  22651. if (rigPostProcess) {
  22652. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22653. if (isPass) {
  22654. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22655. cam.isIntermediate = this._postProcesses.length === 0;
  22656. }
  22657. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22658. rigPostProcess.markTextureDirty();
  22659. }
  22660. else {
  22661. cam._postProcesses = this._postProcesses.slice(0);
  22662. }
  22663. }
  22664. };
  22665. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22666. if (insertAt === void 0) { insertAt = null; }
  22667. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22668. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22669. return 0;
  22670. }
  22671. if (insertAt == null || insertAt < 0) {
  22672. this._postProcesses.push(postProcess);
  22673. }
  22674. else if (this._postProcesses[insertAt] === null) {
  22675. this._postProcesses[insertAt] = postProcess;
  22676. }
  22677. else {
  22678. this._postProcesses.splice(insertAt, 0, postProcess);
  22679. }
  22680. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22681. return this._postProcesses.indexOf(postProcess);
  22682. };
  22683. Camera.prototype.detachPostProcess = function (postProcess) {
  22684. var idx = this._postProcesses.indexOf(postProcess);
  22685. if (idx !== -1) {
  22686. this._postProcesses[idx] = null;
  22687. }
  22688. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22689. };
  22690. Camera.prototype.getWorldMatrix = function () {
  22691. if (this._isSynchronizedViewMatrix()) {
  22692. return this._worldMatrix;
  22693. }
  22694. // Getting the the view matrix will also compute the world matrix.
  22695. this.getViewMatrix();
  22696. return this._worldMatrix;
  22697. };
  22698. Camera.prototype._getViewMatrix = function () {
  22699. return BABYLON.Matrix.Identity();
  22700. };
  22701. Camera.prototype.getViewMatrix = function (force) {
  22702. if (!force && this._isSynchronizedViewMatrix()) {
  22703. return this._computedViewMatrix;
  22704. }
  22705. this.updateCache();
  22706. this._computedViewMatrix = this._getViewMatrix();
  22707. this._currentRenderId = this.getScene().getRenderId();
  22708. this._childRenderId = this._currentRenderId;
  22709. this._refreshFrustumPlanes = true;
  22710. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22711. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22712. }
  22713. this.onViewMatrixChangedObservable.notifyObservers(this);
  22714. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22715. return this._computedViewMatrix;
  22716. };
  22717. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22718. this._doNotComputeProjectionMatrix = true;
  22719. if (projection !== undefined) {
  22720. this._projectionMatrix = projection;
  22721. }
  22722. };
  22723. ;
  22724. Camera.prototype.unfreezeProjectionMatrix = function () {
  22725. this._doNotComputeProjectionMatrix = false;
  22726. };
  22727. ;
  22728. Camera.prototype.getProjectionMatrix = function (force) {
  22729. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22730. return this._projectionMatrix;
  22731. }
  22732. // Cache
  22733. this._cache.mode = this.mode;
  22734. this._cache.minZ = this.minZ;
  22735. this._cache.maxZ = this.maxZ;
  22736. // Matrix
  22737. this._refreshFrustumPlanes = true;
  22738. var engine = this.getEngine();
  22739. var scene = this.getScene();
  22740. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22741. this._cache.fov = this.fov;
  22742. this._cache.fovMode = this.fovMode;
  22743. this._cache.aspectRatio = engine.getAspectRatio(this);
  22744. if (this.minZ <= 0) {
  22745. this.minZ = 0.1;
  22746. }
  22747. if (scene.useRightHandedSystem) {
  22748. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22749. }
  22750. else {
  22751. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22752. }
  22753. }
  22754. else {
  22755. var halfWidth = engine.getRenderWidth() / 2.0;
  22756. var halfHeight = engine.getRenderHeight() / 2.0;
  22757. if (scene.useRightHandedSystem) {
  22758. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22759. }
  22760. else {
  22761. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22762. }
  22763. this._cache.orthoLeft = this.orthoLeft;
  22764. this._cache.orthoRight = this.orthoRight;
  22765. this._cache.orthoBottom = this.orthoBottom;
  22766. this._cache.orthoTop = this.orthoTop;
  22767. this._cache.renderWidth = engine.getRenderWidth();
  22768. this._cache.renderHeight = engine.getRenderHeight();
  22769. }
  22770. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22771. return this._projectionMatrix;
  22772. };
  22773. Camera.prototype.getTranformationMatrix = function () {
  22774. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22775. return this._transformMatrix;
  22776. };
  22777. Camera.prototype.updateFrustumPlanes = function () {
  22778. if (!this._refreshFrustumPlanes) {
  22779. return;
  22780. }
  22781. this.getTranformationMatrix();
  22782. if (!this._frustumPlanes) {
  22783. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22784. }
  22785. else {
  22786. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22787. }
  22788. this._refreshFrustumPlanes = false;
  22789. };
  22790. Camera.prototype.isInFrustum = function (target) {
  22791. this.updateFrustumPlanes();
  22792. return target.isInFrustum(this._frustumPlanes);
  22793. };
  22794. Camera.prototype.isCompletelyInFrustum = function (target) {
  22795. this.updateFrustumPlanes();
  22796. return target.isCompletelyInFrustum(this._frustumPlanes);
  22797. };
  22798. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22799. if (length === void 0) { length = 100; }
  22800. if (!transform) {
  22801. transform = this.getWorldMatrix();
  22802. }
  22803. if (!origin) {
  22804. origin = this.position;
  22805. }
  22806. var forward = new BABYLON.Vector3(0, 0, 1);
  22807. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22808. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22809. return new BABYLON.Ray(origin, direction, length);
  22810. };
  22811. /**
  22812. * Releases resources associated with this node.
  22813. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22814. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22815. */
  22816. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22817. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22818. // Observables
  22819. this.onViewMatrixChangedObservable.clear();
  22820. this.onProjectionMatrixChangedObservable.clear();
  22821. this.onAfterCheckInputsObservable.clear();
  22822. this.onRestoreStateObservable.clear();
  22823. // Inputs
  22824. if (this.inputs) {
  22825. this.inputs.clear();
  22826. }
  22827. // Animations
  22828. this.getScene().stopAnimation(this);
  22829. // Remove from scene
  22830. this.getScene().removeCamera(this);
  22831. while (this._rigCameras.length > 0) {
  22832. var camera = this._rigCameras.pop();
  22833. if (camera) {
  22834. camera.dispose();
  22835. }
  22836. }
  22837. // Postprocesses
  22838. if (this._rigPostProcess) {
  22839. this._rigPostProcess.dispose(this);
  22840. this._rigPostProcess = null;
  22841. this._postProcesses = [];
  22842. }
  22843. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22844. this._rigPostProcess = null;
  22845. this._postProcesses = [];
  22846. }
  22847. else {
  22848. var i = this._postProcesses.length;
  22849. while (--i >= 0) {
  22850. var postProcess = this._postProcesses[i];
  22851. if (postProcess) {
  22852. postProcess.dispose(this);
  22853. }
  22854. }
  22855. }
  22856. // Render targets
  22857. var i = this.customRenderTargets.length;
  22858. while (--i >= 0) {
  22859. this.customRenderTargets[i].dispose();
  22860. }
  22861. this.customRenderTargets = [];
  22862. // Active Meshes
  22863. this._activeMeshes.dispose();
  22864. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22865. };
  22866. Object.defineProperty(Camera.prototype, "leftCamera", {
  22867. // ---- Camera rigs section ----
  22868. get: function () {
  22869. if (this._rigCameras.length < 1) {
  22870. return null;
  22871. }
  22872. return this._rigCameras[0];
  22873. },
  22874. enumerable: true,
  22875. configurable: true
  22876. });
  22877. Object.defineProperty(Camera.prototype, "rightCamera", {
  22878. get: function () {
  22879. if (this._rigCameras.length < 2) {
  22880. return null;
  22881. }
  22882. return this._rigCameras[1];
  22883. },
  22884. enumerable: true,
  22885. configurable: true
  22886. });
  22887. Camera.prototype.getLeftTarget = function () {
  22888. if (this._rigCameras.length < 1) {
  22889. return null;
  22890. }
  22891. return this._rigCameras[0].getTarget();
  22892. };
  22893. Camera.prototype.getRightTarget = function () {
  22894. if (this._rigCameras.length < 2) {
  22895. return null;
  22896. }
  22897. return this._rigCameras[1].getTarget();
  22898. };
  22899. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22900. if (this.cameraRigMode === mode) {
  22901. return;
  22902. }
  22903. while (this._rigCameras.length > 0) {
  22904. var camera = this._rigCameras.pop();
  22905. if (camera) {
  22906. camera.dispose();
  22907. }
  22908. }
  22909. this.cameraRigMode = mode;
  22910. this._cameraRigParams = {};
  22911. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22912. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22913. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22914. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22915. // create the rig cameras, unless none
  22916. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22917. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22918. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22919. if (leftCamera && rightCamera) {
  22920. this._rigCameras.push(leftCamera);
  22921. this._rigCameras.push(rightCamera);
  22922. }
  22923. }
  22924. switch (this.cameraRigMode) {
  22925. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22926. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22927. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22928. break;
  22929. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22930. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22931. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22932. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22933. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22934. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22935. break;
  22936. case Camera.RIG_MODE_VR:
  22937. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22938. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22939. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22940. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22941. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22942. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22943. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22944. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22945. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22946. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22947. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22948. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22949. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22950. if (metrics.compensateDistortion) {
  22951. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22952. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22953. }
  22954. break;
  22955. case Camera.RIG_MODE_WEBVR:
  22956. if (rigParams.vrDisplay) {
  22957. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22958. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22959. //Left eye
  22960. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22961. this._rigCameras[0].setCameraRigParameter("left", true);
  22962. //leaving this for future reference
  22963. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22964. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22965. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22966. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22967. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22968. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22969. this._rigCameras[0].parent = this;
  22970. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22971. //Right eye
  22972. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22973. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22974. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22975. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22976. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22977. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22978. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22979. this._rigCameras[1].parent = this;
  22980. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22981. if (Camera.UseAlternateWebVRRendering) {
  22982. this._rigCameras[1]._skipRendering = true;
  22983. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22984. }
  22985. }
  22986. break;
  22987. }
  22988. this._cascadePostProcessesToRigCams();
  22989. this.update();
  22990. };
  22991. Camera.prototype._getVRProjectionMatrix = function () {
  22992. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22993. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22994. return this._projectionMatrix;
  22995. };
  22996. Camera.prototype._updateCameraRotationMatrix = function () {
  22997. //Here for WebVR
  22998. };
  22999. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23000. //Here for WebVR
  23001. };
  23002. /**
  23003. * This function MUST be overwritten by the different WebVR cameras available.
  23004. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23005. */
  23006. Camera.prototype._getWebVRProjectionMatrix = function () {
  23007. return BABYLON.Matrix.Identity();
  23008. };
  23009. /**
  23010. * This function MUST be overwritten by the different WebVR cameras available.
  23011. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23012. */
  23013. Camera.prototype._getWebVRViewMatrix = function () {
  23014. return BABYLON.Matrix.Identity();
  23015. };
  23016. Camera.prototype.setCameraRigParameter = function (name, value) {
  23017. if (!this._cameraRigParams) {
  23018. this._cameraRigParams = {};
  23019. }
  23020. this._cameraRigParams[name] = value;
  23021. //provisionnally:
  23022. if (name === "interaxialDistance") {
  23023. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23024. }
  23025. };
  23026. /**
  23027. * needs to be overridden by children so sub has required properties to be copied
  23028. */
  23029. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23030. return null;
  23031. };
  23032. /**
  23033. * May need to be overridden by children
  23034. */
  23035. Camera.prototype._updateRigCameras = function () {
  23036. for (var i = 0; i < this._rigCameras.length; i++) {
  23037. this._rigCameras[i].minZ = this.minZ;
  23038. this._rigCameras[i].maxZ = this.maxZ;
  23039. this._rigCameras[i].fov = this.fov;
  23040. }
  23041. // only update viewport when ANAGLYPH
  23042. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23043. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23044. }
  23045. };
  23046. Camera.prototype._setupInputs = function () {
  23047. };
  23048. Camera.prototype.serialize = function () {
  23049. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23050. // Type
  23051. serializationObject.type = this.getClassName();
  23052. // Parent
  23053. if (this.parent) {
  23054. serializationObject.parentId = this.parent.id;
  23055. }
  23056. if (this.inputs) {
  23057. this.inputs.serialize(serializationObject);
  23058. }
  23059. // Animations
  23060. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23061. serializationObject.ranges = this.serializeAnimationRanges();
  23062. return serializationObject;
  23063. };
  23064. Camera.prototype.clone = function (name) {
  23065. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23066. };
  23067. Camera.prototype.getDirection = function (localAxis) {
  23068. var result = BABYLON.Vector3.Zero();
  23069. this.getDirectionToRef(localAxis, result);
  23070. return result;
  23071. };
  23072. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23073. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23074. };
  23075. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23076. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23077. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23078. switch (type) {
  23079. case "ArcRotateCamera":
  23080. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23081. case "DeviceOrientationCamera":
  23082. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23083. case "FollowCamera":
  23084. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23085. case "ArcFollowCamera":
  23086. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23087. case "GamepadCamera":
  23088. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23089. case "TouchCamera":
  23090. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23091. case "VirtualJoysticksCamera":
  23092. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23093. case "WebVRFreeCamera":
  23094. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23095. case "WebVRGamepadCamera":
  23096. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23097. case "VRDeviceOrientationFreeCamera":
  23098. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23099. case "VRDeviceOrientationGamepadCamera":
  23100. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23101. case "AnaglyphArcRotateCamera":
  23102. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23103. case "AnaglyphFreeCamera":
  23104. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23105. case "AnaglyphGamepadCamera":
  23106. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23107. case "AnaglyphUniversalCamera":
  23108. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23109. case "StereoscopicArcRotateCamera":
  23110. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23111. case "StereoscopicFreeCamera":
  23112. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23113. case "StereoscopicGamepadCamera":
  23114. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23115. case "StereoscopicUniversalCamera":
  23116. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23117. case "FreeCamera": // Forcing Universal here
  23118. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23119. default: // Universal Camera is the default value
  23120. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23121. }
  23122. };
  23123. Camera.prototype.computeWorldMatrix = function () {
  23124. return this.getWorldMatrix();
  23125. };
  23126. Camera.Parse = function (parsedCamera, scene) {
  23127. var type = parsedCamera.type;
  23128. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23129. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23130. // Parent
  23131. if (parsedCamera.parentId) {
  23132. camera._waitingParentId = parsedCamera.parentId;
  23133. }
  23134. //If camera has an input manager, let it parse inputs settings
  23135. if (camera.inputs) {
  23136. camera.inputs.parse(parsedCamera);
  23137. camera._setupInputs();
  23138. }
  23139. if (camera.setPosition) { // need to force position
  23140. camera.position.copyFromFloats(0, 0, 0);
  23141. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23142. }
  23143. // Target
  23144. if (parsedCamera.target) {
  23145. if (camera.setTarget) {
  23146. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23147. }
  23148. }
  23149. // Apply 3d rig, when found
  23150. if (parsedCamera.cameraRigMode) {
  23151. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23152. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23153. }
  23154. // Animations
  23155. if (parsedCamera.animations) {
  23156. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23157. var parsedAnimation = parsedCamera.animations[animationIndex];
  23158. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23159. }
  23160. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23161. }
  23162. if (parsedCamera.autoAnimate) {
  23163. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23164. }
  23165. return camera;
  23166. };
  23167. // Statics
  23168. Camera._PERSPECTIVE_CAMERA = 0;
  23169. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23170. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23171. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23172. Camera._RIG_MODE_NONE = 0;
  23173. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23174. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23175. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23176. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23177. Camera._RIG_MODE_VR = 20;
  23178. Camera._RIG_MODE_WEBVR = 21;
  23179. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23180. Camera.UseAlternateWebVRRendering = false;
  23181. __decorate([
  23182. BABYLON.serializeAsVector3()
  23183. ], Camera.prototype, "position", void 0);
  23184. __decorate([
  23185. BABYLON.serializeAsVector3()
  23186. ], Camera.prototype, "upVector", void 0);
  23187. __decorate([
  23188. BABYLON.serialize()
  23189. ], Camera.prototype, "orthoLeft", void 0);
  23190. __decorate([
  23191. BABYLON.serialize()
  23192. ], Camera.prototype, "orthoRight", void 0);
  23193. __decorate([
  23194. BABYLON.serialize()
  23195. ], Camera.prototype, "orthoBottom", void 0);
  23196. __decorate([
  23197. BABYLON.serialize()
  23198. ], Camera.prototype, "orthoTop", void 0);
  23199. __decorate([
  23200. BABYLON.serialize()
  23201. ], Camera.prototype, "fov", void 0);
  23202. __decorate([
  23203. BABYLON.serialize()
  23204. ], Camera.prototype, "minZ", void 0);
  23205. __decorate([
  23206. BABYLON.serialize()
  23207. ], Camera.prototype, "maxZ", void 0);
  23208. __decorate([
  23209. BABYLON.serialize()
  23210. ], Camera.prototype, "inertia", void 0);
  23211. __decorate([
  23212. BABYLON.serialize()
  23213. ], Camera.prototype, "mode", void 0);
  23214. __decorate([
  23215. BABYLON.serialize()
  23216. ], Camera.prototype, "layerMask", void 0);
  23217. __decorate([
  23218. BABYLON.serialize()
  23219. ], Camera.prototype, "fovMode", void 0);
  23220. __decorate([
  23221. BABYLON.serialize()
  23222. ], Camera.prototype, "cameraRigMode", void 0);
  23223. __decorate([
  23224. BABYLON.serialize()
  23225. ], Camera.prototype, "interaxialDistance", void 0);
  23226. __decorate([
  23227. BABYLON.serialize()
  23228. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23229. return Camera;
  23230. }(BABYLON.Node));
  23231. BABYLON.Camera = Camera;
  23232. })(BABYLON || (BABYLON = {}));
  23233. //# sourceMappingURL=babylon.camera.js.map
  23234. var BABYLON;
  23235. (function (BABYLON) {
  23236. var RenderingManager = /** @class */ (function () {
  23237. function RenderingManager(scene) {
  23238. this._renderingGroups = new Array();
  23239. this._autoClearDepthStencil = {};
  23240. this._customOpaqueSortCompareFn = {};
  23241. this._customAlphaTestSortCompareFn = {};
  23242. this._customTransparentSortCompareFn = {};
  23243. this._renderinGroupInfo = null;
  23244. this._scene = scene;
  23245. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23246. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23247. }
  23248. }
  23249. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23250. if (depth === void 0) { depth = true; }
  23251. if (stencil === void 0) { stencil = true; }
  23252. if (this._depthStencilBufferAlreadyCleaned) {
  23253. return;
  23254. }
  23255. this._scene.getEngine().clear(null, false, depth, stencil);
  23256. this._depthStencilBufferAlreadyCleaned = true;
  23257. };
  23258. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23259. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23260. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23261. var info = null;
  23262. if (observable) {
  23263. if (!this._renderinGroupInfo) {
  23264. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23265. }
  23266. info = this._renderinGroupInfo;
  23267. info.scene = this._scene;
  23268. info.camera = this._scene.activeCamera;
  23269. }
  23270. // Dispatch sprites
  23271. if (renderSprites) {
  23272. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23273. var manager = this._scene.spriteManagers[index];
  23274. this.dispatchSprites(manager);
  23275. }
  23276. }
  23277. // Render
  23278. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23279. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23280. var renderingGroup = this._renderingGroups[index];
  23281. if (!renderingGroup && !observable)
  23282. continue;
  23283. var renderingGroupMask = 0;
  23284. // Fire PRECLEAR stage
  23285. if (observable && info) {
  23286. renderingGroupMask = Math.pow(2, index);
  23287. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23288. info.renderingGroupId = index;
  23289. observable.notifyObservers(info, renderingGroupMask);
  23290. }
  23291. // Clear depth/stencil if needed
  23292. if (RenderingManager.AUTOCLEAR) {
  23293. var autoClear = this._autoClearDepthStencil[index];
  23294. if (autoClear && autoClear.autoClear) {
  23295. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23296. }
  23297. }
  23298. if (observable && info) {
  23299. // Fire PREOPAQUE stage
  23300. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23301. observable.notifyObservers(info, renderingGroupMask);
  23302. // Fire PRETRANSPARENT stage
  23303. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23304. observable.notifyObservers(info, renderingGroupMask);
  23305. }
  23306. if (renderingGroup)
  23307. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23308. // Fire POSTTRANSPARENT stage
  23309. if (observable && info) {
  23310. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23311. observable.notifyObservers(info, renderingGroupMask);
  23312. }
  23313. }
  23314. };
  23315. RenderingManager.prototype.reset = function () {
  23316. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23317. var renderingGroup = this._renderingGroups[index];
  23318. if (renderingGroup) {
  23319. renderingGroup.prepare();
  23320. }
  23321. }
  23322. };
  23323. RenderingManager.prototype.dispose = function () {
  23324. this.freeRenderingGroups();
  23325. this._renderingGroups.length = 0;
  23326. };
  23327. /**
  23328. * Clear the info related to rendering groups preventing retention points during dispose.
  23329. */
  23330. RenderingManager.prototype.freeRenderingGroups = function () {
  23331. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23332. var renderingGroup = this._renderingGroups[index];
  23333. if (renderingGroup) {
  23334. renderingGroup.dispose();
  23335. }
  23336. }
  23337. };
  23338. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23339. if (this._renderingGroups[renderingGroupId] === undefined) {
  23340. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23341. }
  23342. };
  23343. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23344. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23345. this._prepareRenderingGroup(renderingGroupId);
  23346. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23347. };
  23348. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23349. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23350. this._prepareRenderingGroup(renderingGroupId);
  23351. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23352. };
  23353. /**
  23354. * @param subMesh The submesh to dispatch
  23355. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23356. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23357. */
  23358. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23359. if (mesh === undefined) {
  23360. mesh = subMesh.getMesh();
  23361. }
  23362. var renderingGroupId = mesh.renderingGroupId || 0;
  23363. this._prepareRenderingGroup(renderingGroupId);
  23364. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23365. };
  23366. /**
  23367. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23368. * This allowed control for front to back rendering or reversly depending of the special needs.
  23369. *
  23370. * @param renderingGroupId The rendering group id corresponding to its index
  23371. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23372. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23373. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23374. */
  23375. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23376. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23377. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23378. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23379. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23380. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23381. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23382. if (this._renderingGroups[renderingGroupId]) {
  23383. var group = this._renderingGroups[renderingGroupId];
  23384. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23385. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23386. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23387. }
  23388. };
  23389. /**
  23390. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23391. *
  23392. * @param renderingGroupId The rendering group id corresponding to its index
  23393. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23394. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23395. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23396. */
  23397. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23398. if (depth === void 0) { depth = true; }
  23399. if (stencil === void 0) { stencil = true; }
  23400. this._autoClearDepthStencil[renderingGroupId] = {
  23401. autoClear: autoClearDepthStencil,
  23402. depth: depth,
  23403. stencil: stencil
  23404. };
  23405. };
  23406. /**
  23407. * The max id used for rendering groups (not included)
  23408. */
  23409. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23410. /**
  23411. * The min id used for rendering groups (included)
  23412. */
  23413. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23414. /**
  23415. * Used to globally prevent autoclearing scenes.
  23416. */
  23417. RenderingManager.AUTOCLEAR = true;
  23418. return RenderingManager;
  23419. }());
  23420. BABYLON.RenderingManager = RenderingManager;
  23421. })(BABYLON || (BABYLON = {}));
  23422. //# sourceMappingURL=babylon.renderingManager.js.map
  23423. var BABYLON;
  23424. (function (BABYLON) {
  23425. var RenderingGroup = /** @class */ (function () {
  23426. /**
  23427. * Creates a new rendering group.
  23428. * @param index The rendering group index
  23429. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23430. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23431. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23432. */
  23433. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23434. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23435. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23436. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23437. this.index = index;
  23438. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23439. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23440. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23441. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23442. this._particleSystems = new BABYLON.SmartArray(256);
  23443. this._spriteManagers = new BABYLON.SmartArray(256);
  23444. this._edgesRenderers = new BABYLON.SmartArray(16);
  23445. this._scene = scene;
  23446. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23447. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23448. this.transparentSortCompareFn = transparentSortCompareFn;
  23449. }
  23450. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23451. /**
  23452. * Set the opaque sort comparison function.
  23453. * If null the sub meshes will be render in the order they were created
  23454. */
  23455. set: function (value) {
  23456. this._opaqueSortCompareFn = value;
  23457. if (value) {
  23458. this._renderOpaque = this.renderOpaqueSorted;
  23459. }
  23460. else {
  23461. this._renderOpaque = RenderingGroup.renderUnsorted;
  23462. }
  23463. },
  23464. enumerable: true,
  23465. configurable: true
  23466. });
  23467. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23468. /**
  23469. * Set the alpha test sort comparison function.
  23470. * If null the sub meshes will be render in the order they were created
  23471. */
  23472. set: function (value) {
  23473. this._alphaTestSortCompareFn = value;
  23474. if (value) {
  23475. this._renderAlphaTest = this.renderAlphaTestSorted;
  23476. }
  23477. else {
  23478. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23479. }
  23480. },
  23481. enumerable: true,
  23482. configurable: true
  23483. });
  23484. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23485. /**
  23486. * Set the transparent sort comparison function.
  23487. * If null the sub meshes will be render in the order they were created
  23488. */
  23489. set: function (value) {
  23490. if (value) {
  23491. this._transparentSortCompareFn = value;
  23492. }
  23493. else {
  23494. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23495. }
  23496. this._renderTransparent = this.renderTransparentSorted;
  23497. },
  23498. enumerable: true,
  23499. configurable: true
  23500. });
  23501. /**
  23502. * Render all the sub meshes contained in the group.
  23503. * @param customRenderFunction Used to override the default render behaviour of the group.
  23504. * @returns true if rendered some submeshes.
  23505. */
  23506. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23507. if (customRenderFunction) {
  23508. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23509. return;
  23510. }
  23511. var engine = this._scene.getEngine();
  23512. // Depth only
  23513. if (this._depthOnlySubMeshes.length !== 0) {
  23514. engine.setColorWrite(false);
  23515. this._renderAlphaTest(this._depthOnlySubMeshes);
  23516. engine.setColorWrite(true);
  23517. }
  23518. // Opaque
  23519. if (this._opaqueSubMeshes.length !== 0) {
  23520. this._renderOpaque(this._opaqueSubMeshes);
  23521. }
  23522. // Alpha test
  23523. if (this._alphaTestSubMeshes.length !== 0) {
  23524. this._renderAlphaTest(this._alphaTestSubMeshes);
  23525. }
  23526. var stencilState = engine.getStencilBuffer();
  23527. engine.setStencilBuffer(false);
  23528. // Sprites
  23529. if (renderSprites) {
  23530. this._renderSprites();
  23531. }
  23532. // Particles
  23533. if (renderParticles) {
  23534. this._renderParticles(activeMeshes);
  23535. }
  23536. if (this.onBeforeTransparentRendering) {
  23537. this.onBeforeTransparentRendering();
  23538. }
  23539. // Transparent
  23540. if (this._transparentSubMeshes.length !== 0) {
  23541. this._renderTransparent(this._transparentSubMeshes);
  23542. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23543. }
  23544. // Set back stencil to false in case it changes before the edge renderer.
  23545. engine.setStencilBuffer(false);
  23546. // Edges
  23547. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23548. this._edgesRenderers.data[edgesRendererIndex].render();
  23549. }
  23550. // Restore Stencil state.
  23551. engine.setStencilBuffer(stencilState);
  23552. };
  23553. /**
  23554. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23555. * @param subMeshes The submeshes to render
  23556. */
  23557. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23558. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23559. };
  23560. /**
  23561. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23562. * @param subMeshes The submeshes to render
  23563. */
  23564. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23565. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23566. };
  23567. /**
  23568. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23569. * @param subMeshes The submeshes to render
  23570. */
  23571. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23572. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23573. };
  23574. /**
  23575. * Renders the submeshes in a specified order.
  23576. * @param subMeshes The submeshes to sort before render
  23577. * @param sortCompareFn The comparison function use to sort
  23578. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23579. * @param transparent Specifies to activate blending if true
  23580. */
  23581. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23582. var subIndex = 0;
  23583. var subMesh;
  23584. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23585. for (; subIndex < subMeshes.length; subIndex++) {
  23586. subMesh = subMeshes.data[subIndex];
  23587. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23588. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23589. }
  23590. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23591. if (sortCompareFn) {
  23592. sortedArray.sort(sortCompareFn);
  23593. }
  23594. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23595. subMesh = sortedArray[subIndex];
  23596. if (transparent) {
  23597. var material = subMesh.getMaterial();
  23598. if (material && material.needDepthPrePass) {
  23599. var engine = material.getScene().getEngine();
  23600. engine.setColorWrite(false);
  23601. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23602. subMesh.render(false);
  23603. engine.setColorWrite(true);
  23604. }
  23605. }
  23606. subMesh.render(transparent);
  23607. }
  23608. };
  23609. /**
  23610. * Renders the submeshes in the order they were dispatched (no sort applied).
  23611. * @param subMeshes The submeshes to render
  23612. */
  23613. RenderingGroup.renderUnsorted = function (subMeshes) {
  23614. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23615. var submesh = subMeshes.data[subIndex];
  23616. submesh.render(false);
  23617. }
  23618. };
  23619. /**
  23620. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23621. * are rendered back to front if in the same alpha index.
  23622. *
  23623. * @param a The first submesh
  23624. * @param b The second submesh
  23625. * @returns The result of the comparison
  23626. */
  23627. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23628. // Alpha index first
  23629. if (a._alphaIndex > b._alphaIndex) {
  23630. return 1;
  23631. }
  23632. if (a._alphaIndex < b._alphaIndex) {
  23633. return -1;
  23634. }
  23635. // Then distance to camera
  23636. return RenderingGroup.backToFrontSortCompare(a, b);
  23637. };
  23638. /**
  23639. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23640. * are rendered back to front.
  23641. *
  23642. * @param a The first submesh
  23643. * @param b The second submesh
  23644. * @returns The result of the comparison
  23645. */
  23646. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23647. // Then distance to camera
  23648. if (a._distanceToCamera < b._distanceToCamera) {
  23649. return 1;
  23650. }
  23651. if (a._distanceToCamera > b._distanceToCamera) {
  23652. return -1;
  23653. }
  23654. return 0;
  23655. };
  23656. /**
  23657. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23658. * are rendered front to back (prevent overdraw).
  23659. *
  23660. * @param a The first submesh
  23661. * @param b The second submesh
  23662. * @returns The result of the comparison
  23663. */
  23664. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23665. // Then distance to camera
  23666. if (a._distanceToCamera < b._distanceToCamera) {
  23667. return -1;
  23668. }
  23669. if (a._distanceToCamera > b._distanceToCamera) {
  23670. return 1;
  23671. }
  23672. return 0;
  23673. };
  23674. /**
  23675. * Resets the different lists of submeshes to prepare a new frame.
  23676. */
  23677. RenderingGroup.prototype.prepare = function () {
  23678. this._opaqueSubMeshes.reset();
  23679. this._transparentSubMeshes.reset();
  23680. this._alphaTestSubMeshes.reset();
  23681. this._depthOnlySubMeshes.reset();
  23682. this._particleSystems.reset();
  23683. this._spriteManagers.reset();
  23684. this._edgesRenderers.reset();
  23685. };
  23686. RenderingGroup.prototype.dispose = function () {
  23687. this._opaqueSubMeshes.dispose();
  23688. this._transparentSubMeshes.dispose();
  23689. this._alphaTestSubMeshes.dispose();
  23690. this._depthOnlySubMeshes.dispose();
  23691. this._particleSystems.dispose();
  23692. this._spriteManagers.dispose();
  23693. this._edgesRenderers.dispose();
  23694. };
  23695. /**
  23696. * Inserts the submesh in its correct queue depending on its material.
  23697. * @param subMesh The submesh to dispatch
  23698. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23699. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23700. */
  23701. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23702. // Get mesh and materials if not provided
  23703. if (mesh === undefined) {
  23704. mesh = subMesh.getMesh();
  23705. }
  23706. if (material === undefined) {
  23707. material = subMesh.getMaterial();
  23708. }
  23709. if (material === null || material === undefined) {
  23710. return;
  23711. }
  23712. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23713. this._transparentSubMeshes.push(subMesh);
  23714. }
  23715. else if (material.needAlphaTesting()) { // Alpha test
  23716. if (material.needDepthPrePass) {
  23717. this._depthOnlySubMeshes.push(subMesh);
  23718. }
  23719. this._alphaTestSubMeshes.push(subMesh);
  23720. }
  23721. else {
  23722. if (material.needDepthPrePass) {
  23723. this._depthOnlySubMeshes.push(subMesh);
  23724. }
  23725. this._opaqueSubMeshes.push(subMesh); // Opaque
  23726. }
  23727. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23728. this._edgesRenderers.push(mesh._edgesRenderer);
  23729. }
  23730. };
  23731. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23732. this._spriteManagers.push(spriteManager);
  23733. };
  23734. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23735. this._particleSystems.push(particleSystem);
  23736. };
  23737. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23738. if (this._particleSystems.length === 0) {
  23739. return;
  23740. }
  23741. // Particles
  23742. var activeCamera = this._scene.activeCamera;
  23743. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23744. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23745. var particleSystem = this._particleSystems.data[particleIndex];
  23746. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23747. continue;
  23748. }
  23749. var emitter = particleSystem.emitter;
  23750. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23751. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23752. }
  23753. }
  23754. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23755. };
  23756. RenderingGroup.prototype._renderSprites = function () {
  23757. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23758. return;
  23759. }
  23760. // Sprites
  23761. var activeCamera = this._scene.activeCamera;
  23762. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23763. for (var id = 0; id < this._spriteManagers.length; id++) {
  23764. var spriteManager = this._spriteManagers.data[id];
  23765. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23766. spriteManager.render();
  23767. }
  23768. }
  23769. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23770. };
  23771. return RenderingGroup;
  23772. }());
  23773. BABYLON.RenderingGroup = RenderingGroup;
  23774. })(BABYLON || (BABYLON = {}));
  23775. //# sourceMappingURL=babylon.renderingGroup.js.map
  23776. var BABYLON;
  23777. (function (BABYLON) {
  23778. /** @hidden */
  23779. var ClickInfo = /** @class */ (function () {
  23780. function ClickInfo() {
  23781. this._singleClick = false;
  23782. this._doubleClick = false;
  23783. this._hasSwiped = false;
  23784. this._ignore = false;
  23785. }
  23786. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23787. get: function () {
  23788. return this._singleClick;
  23789. },
  23790. set: function (b) {
  23791. this._singleClick = b;
  23792. },
  23793. enumerable: true,
  23794. configurable: true
  23795. });
  23796. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23797. get: function () {
  23798. return this._doubleClick;
  23799. },
  23800. set: function (b) {
  23801. this._doubleClick = b;
  23802. },
  23803. enumerable: true,
  23804. configurable: true
  23805. });
  23806. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23807. get: function () {
  23808. return this._hasSwiped;
  23809. },
  23810. set: function (b) {
  23811. this._hasSwiped = b;
  23812. },
  23813. enumerable: true,
  23814. configurable: true
  23815. });
  23816. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23817. get: function () {
  23818. return this._ignore;
  23819. },
  23820. set: function (b) {
  23821. this._ignore = b;
  23822. },
  23823. enumerable: true,
  23824. configurable: true
  23825. });
  23826. return ClickInfo;
  23827. }());
  23828. /**
  23829. * This class is used by the onRenderingGroupObservable
  23830. */
  23831. var RenderingGroupInfo = /** @class */ (function () {
  23832. function RenderingGroupInfo() {
  23833. }
  23834. /**
  23835. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23836. * This stage will be fired no matter what
  23837. */
  23838. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23839. /**
  23840. * Called before opaque object are rendered.
  23841. * This stage will be fired only if there's 3D Opaque content to render
  23842. */
  23843. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23844. /**
  23845. * Called after the opaque objects are rendered and before the transparent ones
  23846. * This stage will be fired only if there's 3D transparent content to render
  23847. */
  23848. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23849. /**
  23850. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23851. * This stage will be fired no matter what
  23852. */
  23853. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23854. return RenderingGroupInfo;
  23855. }());
  23856. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23857. /**
  23858. * Represents a scene to be rendered by the engine.
  23859. * @see http://doc.babylonjs.com/features/scene
  23860. */
  23861. var Scene = /** @class */ (function () {
  23862. /**
  23863. * Creates a new Scene
  23864. * @param engine defines the engine to use to render this scene
  23865. */
  23866. function Scene(engine) {
  23867. // Members
  23868. /**
  23869. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23870. */
  23871. this.autoClear = true;
  23872. /**
  23873. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23874. */
  23875. this.autoClearDepthAndStencil = true;
  23876. /**
  23877. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23878. */
  23879. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23880. /**
  23881. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23882. */
  23883. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23884. this._forceWireframe = false;
  23885. this._forcePointsCloud = false;
  23886. /**
  23887. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23888. */
  23889. this.forceShowBoundingBoxes = false;
  23890. /**
  23891. * Gets or sets a boolean indicating if animations are enabled
  23892. */
  23893. this.animationsEnabled = true;
  23894. this._animationPropertiesOverride = null;
  23895. /**
  23896. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23897. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23898. */
  23899. this.useConstantAnimationDeltaTime = false;
  23900. /**
  23901. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23902. * Please note that it requires to run a ray cast through the scene on every frame
  23903. */
  23904. this.constantlyUpdateMeshUnderPointer = false;
  23905. /**
  23906. * Defines the HTML cursor to use when hovering over interactive elements
  23907. */
  23908. this.hoverCursor = "pointer";
  23909. /**
  23910. * Defines the HTML default cursor to use (empty by default)
  23911. */
  23912. this.defaultCursor = "";
  23913. /**
  23914. * This is used to call preventDefault() on pointer down
  23915. * in order to block unwanted artifacts like system double clicks
  23916. */
  23917. this.preventDefaultOnPointerDown = true;
  23918. // Metadata
  23919. /**
  23920. * Gets or sets user defined metadata
  23921. */
  23922. this.metadata = null;
  23923. /**
  23924. * Use this array to add regular expressions used to disable offline support for specific urls
  23925. */
  23926. this.disableOfflineSupportExceptionRules = new Array();
  23927. /**
  23928. * An event triggered when the scene is disposed.
  23929. */
  23930. this.onDisposeObservable = new BABYLON.Observable();
  23931. this._onDisposeObserver = null;
  23932. /**
  23933. * An event triggered before rendering the scene (right after animations and physics)
  23934. */
  23935. this.onBeforeRenderObservable = new BABYLON.Observable();
  23936. this._onBeforeRenderObserver = null;
  23937. /**
  23938. * An event triggered after rendering the scene
  23939. */
  23940. this.onAfterRenderObservable = new BABYLON.Observable();
  23941. this._onAfterRenderObserver = null;
  23942. /**
  23943. * An event triggered before animating the scene
  23944. */
  23945. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23946. /**
  23947. * An event triggered after animations processing
  23948. */
  23949. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23950. /**
  23951. * An event triggered before draw calls are ready to be sent
  23952. */
  23953. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23954. /**
  23955. * An event triggered after draw calls have been sent
  23956. */
  23957. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23958. /**
  23959. * An event triggered when physic simulation is about to be run
  23960. */
  23961. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23962. /**
  23963. * An event triggered when physic simulation has been done
  23964. */
  23965. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23966. /**
  23967. * An event triggered when the scene is ready
  23968. */
  23969. this.onReadyObservable = new BABYLON.Observable();
  23970. /**
  23971. * An event triggered before rendering a camera
  23972. */
  23973. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23974. this._onBeforeCameraRenderObserver = null;
  23975. /**
  23976. * An event triggered after rendering a camera
  23977. */
  23978. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23979. this._onAfterCameraRenderObserver = null;
  23980. /**
  23981. * An event triggered when active meshes evaluation is about to start
  23982. */
  23983. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23984. /**
  23985. * An event triggered when active meshes evaluation is done
  23986. */
  23987. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23988. /**
  23989. * An event triggered when particles rendering is about to start
  23990. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23991. */
  23992. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23993. /**
  23994. * An event triggered when particles rendering is done
  23995. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23996. */
  23997. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23998. /**
  23999. * An event triggered when sprites rendering is about to start
  24000. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24001. */
  24002. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24003. /**
  24004. * An event triggered when sprites rendering is done
  24005. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24006. */
  24007. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24008. /**
  24009. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24010. */
  24011. this.onDataLoadedObservable = new BABYLON.Observable();
  24012. /**
  24013. * An event triggered when a camera is created
  24014. */
  24015. this.onNewCameraAddedObservable = new BABYLON.Observable();
  24016. /**
  24017. * An event triggered when a camera is removed
  24018. */
  24019. this.onCameraRemovedObservable = new BABYLON.Observable();
  24020. /**
  24021. * An event triggered when a light is created
  24022. */
  24023. this.onNewLightAddedObservable = new BABYLON.Observable();
  24024. /**
  24025. * An event triggered when a light is removed
  24026. */
  24027. this.onLightRemovedObservable = new BABYLON.Observable();
  24028. /**
  24029. * An event triggered when a geometry is created
  24030. */
  24031. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24032. /**
  24033. * An event triggered when a geometry is removed
  24034. */
  24035. this.onGeometryRemovedObservable = new BABYLON.Observable();
  24036. /**
  24037. * An event triggered when a transform node is created
  24038. */
  24039. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24040. /**
  24041. * An event triggered when a transform node is removed
  24042. */
  24043. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24044. /**
  24045. * An event triggered when a mesh is created
  24046. */
  24047. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24048. /**
  24049. * An event triggered when a mesh is removed
  24050. */
  24051. this.onMeshRemovedObservable = new BABYLON.Observable();
  24052. /**
  24053. * An event triggered when render targets are about to be rendered
  24054. * Can happen multiple times per frame.
  24055. */
  24056. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24057. /**
  24058. * An event triggered when render targets were rendered.
  24059. * Can happen multiple times per frame.
  24060. */
  24061. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24062. /**
  24063. * An event triggered before calculating deterministic simulation step
  24064. */
  24065. this.onBeforeStepObservable = new BABYLON.Observable();
  24066. /**
  24067. * An event triggered after calculating deterministic simulation step
  24068. */
  24069. this.onAfterStepObservable = new BABYLON.Observable();
  24070. /**
  24071. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24072. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24073. * 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)
  24074. */
  24075. this.onRenderingGroupObservable = new BABYLON.Observable();
  24076. // Animations
  24077. /**
  24078. * Gets a list of Animations associated with the scene
  24079. */
  24080. this.animations = [];
  24081. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24082. /**
  24083. * 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).
  24084. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24085. */
  24086. this.onPrePointerObservable = new BABYLON.Observable();
  24087. /**
  24088. * Observable event triggered each time an input event is received from the rendering canvas
  24089. */
  24090. this.onPointerObservable = new BABYLON.Observable();
  24091. this._meshPickProceed = false;
  24092. this._currentPickResult = null;
  24093. this._previousPickResult = null;
  24094. this._totalPointersPressed = 0;
  24095. this._doubleClickOccured = false;
  24096. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24097. this.cameraToUseForPointers = null;
  24098. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24099. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24100. this._startingPointerTime = 0;
  24101. this._previousStartingPointerTime = 0;
  24102. this._pointerCaptures = {};
  24103. // Deterministic lockstep
  24104. this._timeAccumulator = 0;
  24105. this._currentStepId = 0;
  24106. this._currentInternalStep = 0;
  24107. // Keyboard
  24108. /**
  24109. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24110. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24111. */
  24112. this.onPreKeyboardObservable = new BABYLON.Observable();
  24113. /**
  24114. * Observable event triggered each time an keyboard event is received from the hosting window
  24115. */
  24116. this.onKeyboardObservable = new BABYLON.Observable();
  24117. // Coordinates system
  24118. this._useRightHandedSystem = false;
  24119. // Fog
  24120. this._fogEnabled = true;
  24121. this._fogMode = Scene.FOGMODE_NONE;
  24122. /**
  24123. * Gets or sets the fog color to use
  24124. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24125. */
  24126. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24127. /**
  24128. * Gets or sets the fog density to use
  24129. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24130. */
  24131. this.fogDensity = 0.1;
  24132. /**
  24133. * Gets or sets the fog start distance to use
  24134. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24135. */
  24136. this.fogStart = 0;
  24137. /**
  24138. * Gets or sets the fog end distance to use
  24139. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24140. */
  24141. this.fogEnd = 1000.0;
  24142. // Lights
  24143. this._shadowsEnabled = true;
  24144. this._lightsEnabled = true;
  24145. /**
  24146. * All of the lights added to this scene
  24147. * @see http://doc.babylonjs.com/babylon101/lights
  24148. */
  24149. this.lights = new Array();
  24150. // Cameras
  24151. /** All of the cameras added to this scene.
  24152. * @see http://doc.babylonjs.com/babylon101/cameras
  24153. */
  24154. this.cameras = new Array();
  24155. /** All of the active cameras added to this scene. */
  24156. this.activeCameras = new Array();
  24157. // Meshes
  24158. /**
  24159. * All of the tranform nodes added to this scene
  24160. * @see http://doc.babylonjs.com/how_to/transformnode
  24161. */
  24162. this.transformNodes = new Array();
  24163. /**
  24164. * All of the (abstract) meshes added to this scene
  24165. */
  24166. this.meshes = new Array();
  24167. /**
  24168. * All of the animation groups added to this scene
  24169. * @see http://doc.babylonjs.com/how_to/group
  24170. */
  24171. this.animationGroups = new Array();
  24172. // Geometries
  24173. this._geometries = new Array();
  24174. /**
  24175. * All of the materials added to this scene
  24176. * @see http://doc.babylonjs.com/babylon101/materials
  24177. */
  24178. this.materials = new Array();
  24179. /**
  24180. * All of the multi-materials added to this scene
  24181. * @see http://doc.babylonjs.com/how_to/multi_materials
  24182. */
  24183. this.multiMaterials = new Array();
  24184. // Textures
  24185. this._texturesEnabled = true;
  24186. /**
  24187. * All of the textures added to this scene
  24188. */
  24189. this.textures = new Array();
  24190. // Particles
  24191. /**
  24192. * Gets or sets a boolean indicating if particles are enabled on this scene
  24193. */
  24194. this.particlesEnabled = true;
  24195. /**
  24196. * All of the particle systems added to this scene
  24197. * @see http://doc.babylonjs.com/babylon101/particles
  24198. */
  24199. this.particleSystems = new Array();
  24200. // Sprites
  24201. /**
  24202. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24203. */
  24204. this.spritesEnabled = true;
  24205. /**
  24206. * All of the sprite managers added to this scene
  24207. * @see http://doc.babylonjs.com/babylon101/sprites
  24208. */
  24209. this.spriteManagers = new Array();
  24210. /**
  24211. * The list of layers (background and foreground) of the scene
  24212. */
  24213. this.layers = new Array();
  24214. /**
  24215. * The list of effect layers (highlights/glow) added to the scene
  24216. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24217. * @see http://doc.babylonjs.com/how_to/glow_layer
  24218. */
  24219. this.effectLayers = new Array();
  24220. // Skeletons
  24221. this._skeletonsEnabled = true;
  24222. /**
  24223. * The list of skeletons added to the scene
  24224. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24225. */
  24226. this.skeletons = new Array();
  24227. // Morph targets
  24228. /**
  24229. * The list of morph target managers added to the scene
  24230. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24231. */
  24232. this.morphTargetManagers = new Array();
  24233. // Lens flares
  24234. /**
  24235. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24236. */
  24237. this.lensFlaresEnabled = true;
  24238. /**
  24239. * The list of lens flare system added to the scene
  24240. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24241. */
  24242. this.lensFlareSystems = new Array();
  24243. // Collisions
  24244. /**
  24245. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24246. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24247. */
  24248. this.collisionsEnabled = true;
  24249. /**
  24250. * Defines the gravity applied to this scene (used only for collisions)
  24251. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24252. */
  24253. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24254. // Postprocesses
  24255. /**
  24256. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24257. */
  24258. this.postProcessesEnabled = true;
  24259. /**
  24260. * The list of postprocesses added to the scene
  24261. */
  24262. this.postProcesses = new Array();
  24263. // Customs render targets
  24264. /**
  24265. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24266. */
  24267. this.renderTargetsEnabled = true;
  24268. /**
  24269. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24270. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24271. */
  24272. this.dumpNextRenderTargets = false;
  24273. /**
  24274. * The list of user defined render targets added to the scene
  24275. */
  24276. this.customRenderTargets = new Array();
  24277. /**
  24278. * Gets the list of meshes imported to the scene through SceneLoader
  24279. */
  24280. this.importedMeshesFiles = new Array();
  24281. // Probes
  24282. /**
  24283. * Gets or sets a boolean indicating if probes are enabled on this scene
  24284. */
  24285. this.probesEnabled = true;
  24286. /**
  24287. * The list of reflection probes added to the scene
  24288. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24289. */
  24290. this.reflectionProbes = new Array();
  24291. /** @hidden */
  24292. this._actionManagers = new Array();
  24293. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24294. // Procedural textures
  24295. /**
  24296. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24297. */
  24298. this.proceduralTexturesEnabled = true;
  24299. /**
  24300. * The list of procedural textures added to the scene
  24301. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24302. */
  24303. this.proceduralTextures = new Array();
  24304. /**
  24305. * The list of sound tracks added to the scene
  24306. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24307. */
  24308. this.soundTracks = new Array();
  24309. this._audioEnabled = true;
  24310. this._headphone = false;
  24311. // Performance counters
  24312. this._totalVertices = new BABYLON.PerfCounter();
  24313. /** @hidden */
  24314. this._activeIndices = new BABYLON.PerfCounter();
  24315. /** @hidden */
  24316. this._activeParticles = new BABYLON.PerfCounter();
  24317. /** @hidden */
  24318. this._activeBones = new BABYLON.PerfCounter();
  24319. this._animationTime = 0;
  24320. /**
  24321. * Gets or sets a general scale for animation speed
  24322. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24323. */
  24324. this.animationTimeScale = 1;
  24325. this._renderId = 0;
  24326. this._executeWhenReadyTimeoutId = -1;
  24327. this._intermediateRendering = false;
  24328. this._viewUpdateFlag = -1;
  24329. this._projectionUpdateFlag = -1;
  24330. this._alternateViewUpdateFlag = -1;
  24331. this._alternateProjectionUpdateFlag = -1;
  24332. /** @hidden */
  24333. this._toBeDisposed = new BABYLON.SmartArray(256);
  24334. this._activeRequests = new Array();
  24335. this._pendingData = new Array();
  24336. this._isDisposed = false;
  24337. /**
  24338. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24339. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24340. */
  24341. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24342. this._activeMeshes = new BABYLON.SmartArray(256);
  24343. this._processedMaterials = new BABYLON.SmartArray(256);
  24344. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24345. /** @hidden */
  24346. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24347. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24348. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24349. /** @hidden */
  24350. this._activeAnimatables = new Array();
  24351. this._transformMatrix = BABYLON.Matrix.Zero();
  24352. this._useAlternateCameraConfiguration = false;
  24353. this._alternateRendering = false;
  24354. /**
  24355. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24356. * This is useful if there are more lights that the maximum simulteanous authorized
  24357. */
  24358. this.requireLightSorting = false;
  24359. this._depthRenderer = {};
  24360. this._activeMeshesFrozen = false;
  24361. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24362. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24363. this._engine.scenes.push(this);
  24364. this._uid = null;
  24365. this._renderingManager = new BABYLON.RenderingManager(this);
  24366. if (BABYLON.PostProcessManager) {
  24367. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24368. }
  24369. if (BABYLON.OutlineRenderer) {
  24370. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24371. }
  24372. if (BABYLON.Tools.IsWindowObjectExist()) {
  24373. this.attachControl();
  24374. }
  24375. //simplification queue
  24376. if (BABYLON.SimplificationQueue) {
  24377. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24378. }
  24379. //collision coordinator initialization. For now legacy per default.
  24380. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24381. // Uniform Buffer
  24382. this._createUbo();
  24383. // Default Image processing definition
  24384. if (BABYLON.ImageProcessingConfiguration) {
  24385. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24386. }
  24387. }
  24388. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24389. /** The fog is deactivated */
  24390. get: function () {
  24391. return Scene._FOGMODE_NONE;
  24392. },
  24393. enumerable: true,
  24394. configurable: true
  24395. });
  24396. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24397. /** The fog density is following an exponential function */
  24398. get: function () {
  24399. return Scene._FOGMODE_EXP;
  24400. },
  24401. enumerable: true,
  24402. configurable: true
  24403. });
  24404. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24405. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24406. get: function () {
  24407. return Scene._FOGMODE_EXP2;
  24408. },
  24409. enumerable: true,
  24410. configurable: true
  24411. });
  24412. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24413. /** The fog density is following a linear function. */
  24414. get: function () {
  24415. return Scene._FOGMODE_LINEAR;
  24416. },
  24417. enumerable: true,
  24418. configurable: true
  24419. });
  24420. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24421. /**
  24422. * Texture used in all pbr material as the reflection texture.
  24423. * As in the majority of the scene they are the same (exception for multi room and so on),
  24424. * this is easier to reference from here than from all the materials.
  24425. */
  24426. get: function () {
  24427. return this._environmentTexture;
  24428. },
  24429. /**
  24430. * Texture used in all pbr material as the reflection texture.
  24431. * As in the majority of the scene they are the same (exception for multi room and so on),
  24432. * this is easier to set here than in all the materials.
  24433. */
  24434. set: function (value) {
  24435. if (this._environmentTexture === value) {
  24436. return;
  24437. }
  24438. this._environmentTexture = value;
  24439. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24440. },
  24441. enumerable: true,
  24442. configurable: true
  24443. });
  24444. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24445. /**
  24446. * Default image processing configuration used either in the rendering
  24447. * Forward main pass or through the imageProcessingPostProcess if present.
  24448. * As in the majority of the scene they are the same (exception for multi camera),
  24449. * this is easier to reference from here than from all the materials and post process.
  24450. *
  24451. * No setter as we it is a shared configuration, you can set the values instead.
  24452. */
  24453. get: function () {
  24454. return this._imageProcessingConfiguration;
  24455. },
  24456. enumerable: true,
  24457. configurable: true
  24458. });
  24459. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24460. get: function () {
  24461. return this._forceWireframe;
  24462. },
  24463. /**
  24464. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24465. */
  24466. set: function (value) {
  24467. if (this._forceWireframe === value) {
  24468. return;
  24469. }
  24470. this._forceWireframe = value;
  24471. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24472. },
  24473. enumerable: true,
  24474. configurable: true
  24475. });
  24476. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24477. get: function () {
  24478. return this._forcePointsCloud;
  24479. },
  24480. /**
  24481. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24482. */
  24483. set: function (value) {
  24484. if (this._forcePointsCloud === value) {
  24485. return;
  24486. }
  24487. this._forcePointsCloud = value;
  24488. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24489. },
  24490. enumerable: true,
  24491. configurable: true
  24492. });
  24493. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24494. /**
  24495. * Gets or sets the animation properties override
  24496. */
  24497. get: function () {
  24498. return this._animationPropertiesOverride;
  24499. },
  24500. set: function (value) {
  24501. this._animationPropertiesOverride = value;
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. Object.defineProperty(Scene.prototype, "onDispose", {
  24507. /** Sets a function to be executed when this scene is disposed. */
  24508. set: function (callback) {
  24509. if (this._onDisposeObserver) {
  24510. this.onDisposeObservable.remove(this._onDisposeObserver);
  24511. }
  24512. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24513. },
  24514. enumerable: true,
  24515. configurable: true
  24516. });
  24517. Object.defineProperty(Scene.prototype, "beforeRender", {
  24518. /** Sets a function to be executed before rendering this scene */
  24519. set: function (callback) {
  24520. if (this._onBeforeRenderObserver) {
  24521. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24522. }
  24523. if (callback) {
  24524. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24525. }
  24526. },
  24527. enumerable: true,
  24528. configurable: true
  24529. });
  24530. Object.defineProperty(Scene.prototype, "afterRender", {
  24531. /** Sets a function to be executed after rendering this scene */
  24532. set: function (callback) {
  24533. if (this._onAfterRenderObserver) {
  24534. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24535. }
  24536. if (callback) {
  24537. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24538. }
  24539. },
  24540. enumerable: true,
  24541. configurable: true
  24542. });
  24543. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24544. /** Sets a function to be executed before rendering a camera*/
  24545. set: function (callback) {
  24546. if (this._onBeforeCameraRenderObserver) {
  24547. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24548. }
  24549. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24550. },
  24551. enumerable: true,
  24552. configurable: true
  24553. });
  24554. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24555. /** Sets a function to be executed after rendering a camera*/
  24556. set: function (callback) {
  24557. if (this._onAfterCameraRenderObserver) {
  24558. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24559. }
  24560. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24561. },
  24562. enumerable: true,
  24563. configurable: true
  24564. });
  24565. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24566. /**
  24567. * Gets the gamepad manager associated with the scene
  24568. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24569. */
  24570. get: function () {
  24571. if (!this._gamepadManager) {
  24572. this._gamepadManager = new BABYLON.GamepadManager(this);
  24573. }
  24574. return this._gamepadManager;
  24575. },
  24576. enumerable: true,
  24577. configurable: true
  24578. });
  24579. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24580. /**
  24581. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24582. */
  24583. get: function () {
  24584. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24585. },
  24586. enumerable: true,
  24587. configurable: true
  24588. });
  24589. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24590. get: function () {
  24591. return this._useRightHandedSystem;
  24592. },
  24593. /**
  24594. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24595. */
  24596. set: function (value) {
  24597. if (this._useRightHandedSystem === value) {
  24598. return;
  24599. }
  24600. this._useRightHandedSystem = value;
  24601. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24602. },
  24603. enumerable: true,
  24604. configurable: true
  24605. });
  24606. /**
  24607. * Sets the step Id used by deterministic lock step
  24608. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24609. * @param newStepId defines the step Id
  24610. */
  24611. Scene.prototype.setStepId = function (newStepId) {
  24612. this._currentStepId = newStepId;
  24613. };
  24614. ;
  24615. /**
  24616. * Gets the step Id used by deterministic lock step
  24617. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24618. * @returns the step Id
  24619. */
  24620. Scene.prototype.getStepId = function () {
  24621. return this._currentStepId;
  24622. };
  24623. ;
  24624. /**
  24625. * Gets the internal step used by deterministic lock step
  24626. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24627. * @returns the internal step
  24628. */
  24629. Scene.prototype.getInternalStep = function () {
  24630. return this._currentInternalStep;
  24631. };
  24632. ;
  24633. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24634. get: function () {
  24635. return this._fogEnabled;
  24636. },
  24637. /**
  24638. * Gets or sets a boolean indicating if fog is enabled on this scene
  24639. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24640. */
  24641. set: function (value) {
  24642. if (this._fogEnabled === value) {
  24643. return;
  24644. }
  24645. this._fogEnabled = value;
  24646. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24647. },
  24648. enumerable: true,
  24649. configurable: true
  24650. });
  24651. Object.defineProperty(Scene.prototype, "fogMode", {
  24652. get: function () {
  24653. return this._fogMode;
  24654. },
  24655. /**
  24656. * Gets or sets the fog mode to use
  24657. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24658. */
  24659. set: function (value) {
  24660. if (this._fogMode === value) {
  24661. return;
  24662. }
  24663. this._fogMode = value;
  24664. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24665. },
  24666. enumerable: true,
  24667. configurable: true
  24668. });
  24669. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24670. get: function () {
  24671. return this._shadowsEnabled;
  24672. },
  24673. /**
  24674. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24675. */
  24676. set: function (value) {
  24677. if (this._shadowsEnabled === value) {
  24678. return;
  24679. }
  24680. this._shadowsEnabled = value;
  24681. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24682. },
  24683. enumerable: true,
  24684. configurable: true
  24685. });
  24686. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24687. get: function () {
  24688. return this._lightsEnabled;
  24689. },
  24690. /**
  24691. * Gets or sets a boolean indicating if lights are enabled on this scene
  24692. */
  24693. set: function (value) {
  24694. if (this._lightsEnabled === value) {
  24695. return;
  24696. }
  24697. this._lightsEnabled = value;
  24698. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24699. },
  24700. enumerable: true,
  24701. configurable: true
  24702. });
  24703. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24704. /** The default material used on meshes when no material is affected */
  24705. get: function () {
  24706. if (!this._defaultMaterial) {
  24707. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24708. }
  24709. return this._defaultMaterial;
  24710. },
  24711. /** The default material used on meshes when no material is affected */
  24712. set: function (value) {
  24713. this._defaultMaterial = value;
  24714. },
  24715. enumerable: true,
  24716. configurable: true
  24717. });
  24718. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24719. get: function () {
  24720. return this._texturesEnabled;
  24721. },
  24722. /**
  24723. * Gets or sets a boolean indicating if textures are enabled on this scene
  24724. */
  24725. set: function (value) {
  24726. if (this._texturesEnabled === value) {
  24727. return;
  24728. }
  24729. this._texturesEnabled = value;
  24730. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24736. get: function () {
  24737. return this._skeletonsEnabled;
  24738. },
  24739. /**
  24740. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24741. */
  24742. set: function (value) {
  24743. if (this._skeletonsEnabled === value) {
  24744. return;
  24745. }
  24746. this._skeletonsEnabled = value;
  24747. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24748. },
  24749. enumerable: true,
  24750. configurable: true
  24751. });
  24752. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24753. /**
  24754. * Gets the postprocess render pipeline manager
  24755. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24756. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24757. */
  24758. get: function () {
  24759. if (!this._postProcessRenderPipelineManager) {
  24760. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24761. }
  24762. return this._postProcessRenderPipelineManager;
  24763. },
  24764. enumerable: true,
  24765. configurable: true
  24766. });
  24767. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24768. /**
  24769. * Gets the main soundtrack associated with the scene
  24770. */
  24771. get: function () {
  24772. if (!this._mainSoundTrack) {
  24773. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24774. }
  24775. return this._mainSoundTrack;
  24776. },
  24777. enumerable: true,
  24778. configurable: true
  24779. });
  24780. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24781. /** @hidden */
  24782. get: function () {
  24783. return this._alternateRendering;
  24784. },
  24785. enumerable: true,
  24786. configurable: true
  24787. });
  24788. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24789. /**
  24790. * Gets the list of frustum planes (built from the active camera)
  24791. */
  24792. get: function () {
  24793. return this._frustumPlanes;
  24794. },
  24795. enumerable: true,
  24796. configurable: true
  24797. });
  24798. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24799. /**
  24800. * Gets the current geometry buffer associated to the scene.
  24801. */
  24802. get: function () {
  24803. return this._geometryBufferRenderer;
  24804. },
  24805. /**
  24806. * Sets the current geometry buffer for the scene.
  24807. */
  24808. set: function (geometryBufferRenderer) {
  24809. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24810. this._geometryBufferRenderer = geometryBufferRenderer;
  24811. }
  24812. },
  24813. enumerable: true,
  24814. configurable: true
  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 bounding box renderer associated with the scene
  24928. * @returns a BoundingBoxRenderer
  24929. */
  24930. Scene.prototype.getBoundingBoxRenderer = function () {
  24931. if (!this._boundingBoxRenderer) {
  24932. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24933. }
  24934. return this._boundingBoxRenderer;
  24935. };
  24936. /**
  24937. * Gets the outline renderer associated with the scene
  24938. * @returns a OutlineRenderer
  24939. */
  24940. Scene.prototype.getOutlineRenderer = function () {
  24941. return this._outlineRenderer;
  24942. };
  24943. /**
  24944. * Gets the engine associated with the scene
  24945. * @returns an Engine
  24946. */
  24947. Scene.prototype.getEngine = function () {
  24948. return this._engine;
  24949. };
  24950. /**
  24951. * Gets the total number of vertices rendered per frame
  24952. * @returns the total number of vertices rendered per frame
  24953. */
  24954. Scene.prototype.getTotalVertices = function () {
  24955. return this._totalVertices.current;
  24956. };
  24957. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24958. /**
  24959. * Gets the performance counter for total vertices
  24960. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24961. */
  24962. get: function () {
  24963. return this._totalVertices;
  24964. },
  24965. enumerable: true,
  24966. configurable: true
  24967. });
  24968. /**
  24969. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24970. * @returns the total number of active indices rendered per frame
  24971. */
  24972. Scene.prototype.getActiveIndices = function () {
  24973. return this._activeIndices.current;
  24974. };
  24975. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24976. /**
  24977. * Gets the performance counter for active indices
  24978. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24979. */
  24980. get: function () {
  24981. return this._activeIndices;
  24982. },
  24983. enumerable: true,
  24984. configurable: true
  24985. });
  24986. /**
  24987. * Gets the total number of active particles rendered per frame
  24988. * @returns the total number of active particles rendered per frame
  24989. */
  24990. Scene.prototype.getActiveParticles = function () {
  24991. return this._activeParticles.current;
  24992. };
  24993. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24994. /**
  24995. * Gets the performance counter for active particles
  24996. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24997. */
  24998. get: function () {
  24999. return this._activeParticles;
  25000. },
  25001. enumerable: true,
  25002. configurable: true
  25003. });
  25004. /**
  25005. * Gets the total number of active bones rendered per frame
  25006. * @returns the total number of active bones rendered per frame
  25007. */
  25008. Scene.prototype.getActiveBones = function () {
  25009. return this._activeBones.current;
  25010. };
  25011. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25012. /**
  25013. * Gets the performance counter for active bones
  25014. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25015. */
  25016. get: function () {
  25017. return this._activeBones;
  25018. },
  25019. enumerable: true,
  25020. configurable: true
  25021. });
  25022. /** @hidden */
  25023. Scene.prototype.getInterFramePerfCounter = function () {
  25024. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25025. return 0;
  25026. };
  25027. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25028. /** @hidden */
  25029. get: function () {
  25030. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25031. return null;
  25032. },
  25033. enumerable: true,
  25034. configurable: true
  25035. });
  25036. /** @hidden */
  25037. Scene.prototype.getLastFrameDuration = function () {
  25038. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25039. return 0;
  25040. };
  25041. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25042. /** @hidden */
  25043. get: function () {
  25044. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25045. return null;
  25046. },
  25047. enumerable: true,
  25048. configurable: true
  25049. });
  25050. /** @hidden */
  25051. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25052. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25053. return 0;
  25054. };
  25055. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25056. /** @hidden */
  25057. get: function () {
  25058. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25059. return null;
  25060. },
  25061. enumerable: true,
  25062. configurable: true
  25063. });
  25064. /**
  25065. * Gets the array of active meshes
  25066. * @returns an array of AbstractMesh
  25067. */
  25068. Scene.prototype.getActiveMeshes = function () {
  25069. return this._activeMeshes;
  25070. };
  25071. /** @hidden */
  25072. Scene.prototype.getRenderTargetsDuration = function () {
  25073. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25074. return 0;
  25075. };
  25076. /** @hidden */
  25077. Scene.prototype.getRenderDuration = function () {
  25078. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25079. return 0;
  25080. };
  25081. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25082. /** @hidden */
  25083. get: function () {
  25084. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25085. return null;
  25086. },
  25087. enumerable: true,
  25088. configurable: true
  25089. });
  25090. /** @hidden */
  25091. Scene.prototype.getParticlesDuration = function () {
  25092. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25093. return 0;
  25094. };
  25095. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25096. /** @hidden */
  25097. get: function () {
  25098. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25099. return null;
  25100. },
  25101. enumerable: true,
  25102. configurable: true
  25103. });
  25104. /** @hidden */
  25105. Scene.prototype.getSpritesDuration = function () {
  25106. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25107. return 0;
  25108. };
  25109. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25110. /** @hidden */
  25111. get: function () {
  25112. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25113. return null;
  25114. },
  25115. enumerable: true,
  25116. configurable: true
  25117. });
  25118. /**
  25119. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25120. * @returns a number
  25121. */
  25122. Scene.prototype.getAnimationRatio = function () {
  25123. return this._animationRatio;
  25124. };
  25125. /**
  25126. * Gets an unique Id for the current frame
  25127. * @returns a number
  25128. */
  25129. Scene.prototype.getRenderId = function () {
  25130. return this._renderId;
  25131. };
  25132. /** Call this function if you want to manually increment the render Id*/
  25133. Scene.prototype.incrementRenderId = function () {
  25134. this._renderId++;
  25135. };
  25136. Scene.prototype._updatePointerPosition = function (evt) {
  25137. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25138. if (!canvasRect) {
  25139. return;
  25140. }
  25141. this._pointerX = evt.clientX - canvasRect.left;
  25142. this._pointerY = evt.clientY - canvasRect.top;
  25143. this._unTranslatedPointerX = this._pointerX;
  25144. this._unTranslatedPointerY = this._pointerY;
  25145. };
  25146. Scene.prototype._createUbo = function () {
  25147. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25148. this._sceneUbo.addUniform("viewProjection", 16);
  25149. this._sceneUbo.addUniform("view", 16);
  25150. };
  25151. Scene.prototype._createAlternateUbo = function () {
  25152. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25153. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25154. this._alternateSceneUbo.addUniform("view", 16);
  25155. };
  25156. // Pointers handling
  25157. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25158. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25159. if (result) {
  25160. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25161. }
  25162. return result;
  25163. };
  25164. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25165. if (pointerInfo.pickInfo) {
  25166. if (!pointerInfo.pickInfo.ray) {
  25167. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25168. }
  25169. }
  25170. };
  25171. /**
  25172. * Use this method to simulate a pointer move on a mesh
  25173. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25174. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25175. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25176. * @returns the current scene
  25177. */
  25178. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25179. var evt = new PointerEvent("pointermove", pointerEventInit);
  25180. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25181. return this;
  25182. }
  25183. return this._processPointerMove(pickResult, evt);
  25184. };
  25185. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25186. var canvas = this._engine.getRenderingCanvas();
  25187. if (!canvas) {
  25188. return this;
  25189. }
  25190. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25191. this.setPointerOverSprite(null);
  25192. this.setPointerOverMesh(pickResult.pickedMesh);
  25193. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25194. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25195. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25196. }
  25197. else {
  25198. canvas.style.cursor = this.hoverCursor;
  25199. }
  25200. }
  25201. else {
  25202. canvas.style.cursor = this.defaultCursor;
  25203. }
  25204. }
  25205. else {
  25206. this.setPointerOverMesh(null);
  25207. // Sprites
  25208. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25209. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25210. this.setPointerOverSprite(pickResult.pickedSprite);
  25211. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25212. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25213. }
  25214. else {
  25215. canvas.style.cursor = this.hoverCursor;
  25216. }
  25217. }
  25218. else {
  25219. this.setPointerOverSprite(null);
  25220. // Restore pointer
  25221. canvas.style.cursor = this.defaultCursor;
  25222. }
  25223. }
  25224. if (pickResult) {
  25225. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25226. if (this.onPointerMove) {
  25227. this.onPointerMove(evt, pickResult, type);
  25228. }
  25229. if (this.onPointerObservable.hasObservers()) {
  25230. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25231. this._setRayOnPointerInfo(pi);
  25232. this.onPointerObservable.notifyObservers(pi, type);
  25233. }
  25234. }
  25235. return this;
  25236. };
  25237. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25238. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25239. if (pickResult) {
  25240. pi.ray = pickResult.ray;
  25241. }
  25242. this.onPrePointerObservable.notifyObservers(pi, type);
  25243. if (pi.skipOnPointerObservable) {
  25244. return true;
  25245. }
  25246. else {
  25247. return false;
  25248. }
  25249. };
  25250. /**
  25251. * Use this method to simulate a pointer down on a mesh
  25252. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25253. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25254. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25255. * @returns the current scene
  25256. */
  25257. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25258. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25259. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25260. return this;
  25261. }
  25262. return this._processPointerDown(pickResult, evt);
  25263. };
  25264. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25265. var _this = this;
  25266. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25267. this._pickedDownMesh = pickResult.pickedMesh;
  25268. var actionManager = pickResult.pickedMesh.actionManager;
  25269. if (actionManager) {
  25270. if (actionManager.hasPickTriggers) {
  25271. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25272. switch (evt.button) {
  25273. case 0:
  25274. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25275. break;
  25276. case 1:
  25277. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25278. break;
  25279. case 2:
  25280. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25281. break;
  25282. }
  25283. }
  25284. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25285. window.setTimeout(function () {
  25286. 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);
  25287. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25288. if (_this._totalPointersPressed !== 0 &&
  25289. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25290. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25291. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25292. _this._startingPointerTime = 0;
  25293. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25294. }
  25295. }
  25296. }, Scene.LongPressDelay);
  25297. }
  25298. }
  25299. }
  25300. if (pickResult) {
  25301. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25302. if (this.onPointerDown) {
  25303. this.onPointerDown(evt, pickResult, type);
  25304. }
  25305. if (this.onPointerObservable.hasObservers()) {
  25306. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25307. this._setRayOnPointerInfo(pi);
  25308. this.onPointerObservable.notifyObservers(pi, type);
  25309. }
  25310. }
  25311. return this;
  25312. };
  25313. /**
  25314. * Use this method to simulate a pointer up on a mesh
  25315. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25316. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25317. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25318. * @returns the current scene
  25319. */
  25320. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25321. var evt = new PointerEvent("pointerup", pointerEventInit);
  25322. var clickInfo = new ClickInfo();
  25323. clickInfo.singleClick = true;
  25324. clickInfo.ignore = true;
  25325. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25326. return this;
  25327. }
  25328. return this._processPointerUp(pickResult, evt, clickInfo);
  25329. };
  25330. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25331. if (pickResult && pickResult && pickResult.pickedMesh) {
  25332. this._pickedUpMesh = pickResult.pickedMesh;
  25333. if (this._pickedDownMesh === this._pickedUpMesh) {
  25334. if (this.onPointerPick) {
  25335. this.onPointerPick(evt, pickResult);
  25336. }
  25337. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25338. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25339. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25340. this._setRayOnPointerInfo(pi);
  25341. this.onPointerObservable.notifyObservers(pi, type_1);
  25342. }
  25343. }
  25344. if (pickResult.pickedMesh.actionManager) {
  25345. if (clickInfo.ignore) {
  25346. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25347. }
  25348. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25349. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25350. }
  25351. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25352. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25353. }
  25354. }
  25355. }
  25356. if (this._pickedDownMesh &&
  25357. this._pickedDownMesh.actionManager &&
  25358. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25359. this._pickedDownMesh !== this._pickedUpMesh) {
  25360. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25361. }
  25362. var type = BABYLON.PointerEventTypes.POINTERUP;
  25363. if (this.onPointerObservable.hasObservers()) {
  25364. if (!clickInfo.ignore) {
  25365. if (!clickInfo.hasSwiped) {
  25366. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25367. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25368. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25369. this._setRayOnPointerInfo(pi);
  25370. this.onPointerObservable.notifyObservers(pi, type_2);
  25371. }
  25372. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25373. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25374. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25375. this._setRayOnPointerInfo(pi);
  25376. this.onPointerObservable.notifyObservers(pi, type_3);
  25377. }
  25378. }
  25379. }
  25380. else {
  25381. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25382. this._setRayOnPointerInfo(pi);
  25383. this.onPointerObservable.notifyObservers(pi, type);
  25384. }
  25385. }
  25386. if (this.onPointerUp) {
  25387. this.onPointerUp(evt, pickResult, type);
  25388. }
  25389. return this;
  25390. };
  25391. /**
  25392. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25393. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25394. * @returns true if the pointer was captured
  25395. */
  25396. Scene.prototype.isPointerCaptured = function (pointerId) {
  25397. if (pointerId === void 0) { pointerId = 0; }
  25398. return this._pointerCaptures[pointerId];
  25399. };
  25400. /**
  25401. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25402. * @param attachUp defines if you want to attach events to pointerup
  25403. * @param attachDown defines if you want to attach events to pointerdown
  25404. * @param attachMove defines if you want to attach events to pointermove
  25405. */
  25406. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25407. var _this = this;
  25408. if (attachUp === void 0) { attachUp = true; }
  25409. if (attachDown === void 0) { attachDown = true; }
  25410. if (attachMove === void 0) { attachMove = true; }
  25411. this._initActionManager = function (act, clickInfo) {
  25412. if (!_this._meshPickProceed) {
  25413. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25414. _this._currentPickResult = pickResult;
  25415. if (pickResult) {
  25416. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25417. }
  25418. _this._meshPickProceed = true;
  25419. }
  25420. return act;
  25421. };
  25422. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25423. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25424. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25425. btn !== _this._previousButtonPressed) {
  25426. _this._doubleClickOccured = false;
  25427. clickInfo.singleClick = true;
  25428. clickInfo.ignore = false;
  25429. cb(clickInfo, _this._currentPickResult);
  25430. }
  25431. };
  25432. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25433. var clickInfo = new ClickInfo();
  25434. _this._currentPickResult = null;
  25435. var act = null;
  25436. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25437. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25438. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25439. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25440. act = _this._initActionManager(act, clickInfo);
  25441. if (act)
  25442. checkPicking = act.hasPickTriggers;
  25443. }
  25444. if (checkPicking) {
  25445. var btn = evt.button;
  25446. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25447. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25448. if (!clickInfo.hasSwiped) {
  25449. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25450. if (!checkSingleClickImmediately) {
  25451. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25452. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25453. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25454. act = _this._initActionManager(act, clickInfo);
  25455. if (act)
  25456. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25457. }
  25458. }
  25459. if (checkSingleClickImmediately) {
  25460. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25461. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25462. btn !== _this._previousButtonPressed) {
  25463. clickInfo.singleClick = true;
  25464. cb(clickInfo, _this._currentPickResult);
  25465. }
  25466. }
  25467. // at least one double click is required to be check and exclusive double click is enabled
  25468. else {
  25469. // wait that no double click has been raised during the double click delay
  25470. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25471. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25472. }
  25473. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25474. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25475. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25476. act = _this._initActionManager(act, clickInfo);
  25477. if (act)
  25478. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25479. }
  25480. if (checkDoubleClick) {
  25481. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25482. if (btn === _this._previousButtonPressed &&
  25483. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25484. !_this._doubleClickOccured) {
  25485. // pointer has not moved for 2 clicks, it's a double click
  25486. if (!clickInfo.hasSwiped &&
  25487. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25488. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25489. _this._previousStartingPointerTime = 0;
  25490. _this._doubleClickOccured = true;
  25491. clickInfo.doubleClick = true;
  25492. clickInfo.ignore = false;
  25493. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25494. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25495. }
  25496. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25497. cb(clickInfo, _this._currentPickResult);
  25498. }
  25499. // if the two successive clicks are too far, it's just two simple clicks
  25500. else {
  25501. _this._doubleClickOccured = false;
  25502. _this._previousStartingPointerTime = _this._startingPointerTime;
  25503. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25504. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25505. _this._previousButtonPressed = btn;
  25506. if (Scene.ExclusiveDoubleClickMode) {
  25507. if (_this._previousDelayedSimpleClickTimeout) {
  25508. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25509. }
  25510. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25511. cb(clickInfo, _this._previousPickResult);
  25512. }
  25513. else {
  25514. cb(clickInfo, _this._currentPickResult);
  25515. }
  25516. }
  25517. }
  25518. // just the first click of the double has been raised
  25519. else {
  25520. _this._doubleClickOccured = false;
  25521. _this._previousStartingPointerTime = _this._startingPointerTime;
  25522. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25523. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25524. _this._previousButtonPressed = btn;
  25525. }
  25526. }
  25527. }
  25528. }
  25529. clickInfo.ignore = true;
  25530. cb(clickInfo, _this._currentPickResult);
  25531. };
  25532. this._spritePredicate = function (sprite) {
  25533. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25534. };
  25535. this._onPointerMove = function (evt) {
  25536. _this._updatePointerPosition(evt);
  25537. // PreObservable support
  25538. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25539. return;
  25540. }
  25541. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25542. return;
  25543. }
  25544. if (!_this.pointerMovePredicate) {
  25545. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25546. }
  25547. // Meshes
  25548. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25549. _this._processPointerMove(pickResult, evt);
  25550. };
  25551. this._onPointerDown = function (evt) {
  25552. _this._totalPointersPressed++;
  25553. _this._pickedDownMesh = null;
  25554. _this._meshPickProceed = false;
  25555. _this._updatePointerPosition(evt);
  25556. if (_this.preventDefaultOnPointerDown && canvas) {
  25557. evt.preventDefault();
  25558. canvas.focus();
  25559. }
  25560. // PreObservable support
  25561. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25562. return;
  25563. }
  25564. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25565. return;
  25566. }
  25567. _this._pointerCaptures[evt.pointerId] = true;
  25568. _this._startingPointerPosition.x = _this._pointerX;
  25569. _this._startingPointerPosition.y = _this._pointerY;
  25570. _this._startingPointerTime = Date.now();
  25571. if (!_this.pointerDownPredicate) {
  25572. _this.pointerDownPredicate = function (mesh) {
  25573. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25574. };
  25575. }
  25576. // Meshes
  25577. _this._pickedDownMesh = null;
  25578. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25579. _this._processPointerDown(pickResult, evt);
  25580. // Sprites
  25581. _this._pickedDownSprite = null;
  25582. if (_this.spriteManagers.length > 0) {
  25583. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25584. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25585. if (pickResult.pickedSprite.actionManager) {
  25586. _this._pickedDownSprite = pickResult.pickedSprite;
  25587. switch (evt.button) {
  25588. case 0:
  25589. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25590. break;
  25591. case 1:
  25592. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25593. break;
  25594. case 2:
  25595. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25596. break;
  25597. }
  25598. if (pickResult.pickedSprite.actionManager) {
  25599. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25600. }
  25601. }
  25602. }
  25603. }
  25604. };
  25605. this._onPointerUp = function (evt) {
  25606. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25607. return; // So we need to test it the pointer down was pressed before.
  25608. }
  25609. _this._totalPointersPressed--;
  25610. _this._pickedUpMesh = null;
  25611. _this._meshPickProceed = false;
  25612. _this._updatePointerPosition(evt);
  25613. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25614. // PreObservable support
  25615. if (_this.onPrePointerObservable.hasObservers()) {
  25616. if (!clickInfo.ignore) {
  25617. if (!clickInfo.hasSwiped) {
  25618. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25619. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25620. return;
  25621. }
  25622. }
  25623. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25624. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25625. return;
  25626. }
  25627. }
  25628. }
  25629. }
  25630. else {
  25631. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25632. return;
  25633. }
  25634. }
  25635. }
  25636. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25637. return;
  25638. }
  25639. _this._pointerCaptures[evt.pointerId] = false;
  25640. if (!_this.pointerUpPredicate) {
  25641. _this.pointerUpPredicate = function (mesh) {
  25642. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25643. };
  25644. }
  25645. // Meshes
  25646. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25647. _this._initActionManager(null, clickInfo);
  25648. }
  25649. if (!pickResult) {
  25650. pickResult = _this._currentPickResult;
  25651. }
  25652. _this._processPointerUp(pickResult, evt, clickInfo);
  25653. // Sprites
  25654. if (!clickInfo.ignore) {
  25655. if (_this.spriteManagers.length > 0) {
  25656. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25657. if (spritePickResult) {
  25658. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25659. if (spritePickResult.pickedSprite.actionManager) {
  25660. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25661. if (spritePickResult.pickedSprite.actionManager) {
  25662. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25663. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25664. }
  25665. }
  25666. }
  25667. }
  25668. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25669. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25670. }
  25671. }
  25672. }
  25673. }
  25674. _this._previousPickResult = _this._currentPickResult;
  25675. });
  25676. };
  25677. this._onKeyDown = function (evt) {
  25678. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25679. if (_this.onPreKeyboardObservable.hasObservers()) {
  25680. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25681. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25682. if (pi.skipOnPointerObservable) {
  25683. return;
  25684. }
  25685. }
  25686. if (_this.onKeyboardObservable.hasObservers()) {
  25687. var pi = new BABYLON.KeyboardInfo(type, evt);
  25688. _this.onKeyboardObservable.notifyObservers(pi, type);
  25689. }
  25690. if (_this.actionManager) {
  25691. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25692. }
  25693. };
  25694. this._onKeyUp = function (evt) {
  25695. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25696. if (_this.onPreKeyboardObservable.hasObservers()) {
  25697. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25698. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25699. if (pi.skipOnPointerObservable) {
  25700. return;
  25701. }
  25702. }
  25703. if (_this.onKeyboardObservable.hasObservers()) {
  25704. var pi = new BABYLON.KeyboardInfo(type, evt);
  25705. _this.onKeyboardObservable.notifyObservers(pi, type);
  25706. }
  25707. if (_this.actionManager) {
  25708. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25709. }
  25710. };
  25711. var engine = this.getEngine();
  25712. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25713. if (!canvas) {
  25714. return;
  25715. }
  25716. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25717. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25718. });
  25719. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25720. if (!canvas) {
  25721. return;
  25722. }
  25723. canvas.removeEventListener("keydown", _this._onKeyDown);
  25724. canvas.removeEventListener("keyup", _this._onKeyUp);
  25725. });
  25726. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25727. var canvas = this._engine.getRenderingCanvas();
  25728. if (!canvas) {
  25729. return;
  25730. }
  25731. if (attachMove) {
  25732. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25733. // Wheel
  25734. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25735. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25736. }
  25737. if (attachDown) {
  25738. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25739. }
  25740. if (attachUp) {
  25741. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25742. }
  25743. canvas.tabIndex = 1;
  25744. };
  25745. /** Detaches all event handlers*/
  25746. Scene.prototype.detachControl = function () {
  25747. var engine = this.getEngine();
  25748. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25749. var canvas = engine.getRenderingCanvas();
  25750. if (!canvas) {
  25751. return;
  25752. }
  25753. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25754. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25755. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25756. if (this._onCanvasBlurObserver) {
  25757. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25758. }
  25759. if (this._onCanvasFocusObserver) {
  25760. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25761. }
  25762. // Wheel
  25763. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25764. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25765. // Keyboard
  25766. canvas.removeEventListener("keydown", this._onKeyDown);
  25767. canvas.removeEventListener("keyup", this._onKeyUp);
  25768. // Observables
  25769. this.onKeyboardObservable.clear();
  25770. this.onPreKeyboardObservable.clear();
  25771. this.onPointerObservable.clear();
  25772. this.onPrePointerObservable.clear();
  25773. };
  25774. /**
  25775. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25776. * Delay loaded resources are not taking in account
  25777. * @return true if all required resources are ready
  25778. */
  25779. Scene.prototype.isReady = function () {
  25780. if (this._isDisposed) {
  25781. return false;
  25782. }
  25783. if (this._pendingData.length > 0) {
  25784. return false;
  25785. }
  25786. var index;
  25787. var engine = this.getEngine();
  25788. // Geometries
  25789. for (index = 0; index < this._geometries.length; index++) {
  25790. var geometry = this._geometries[index];
  25791. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25792. return false;
  25793. }
  25794. }
  25795. // Meshes
  25796. for (index = 0; index < this.meshes.length; index++) {
  25797. var mesh = this.meshes[index];
  25798. if (!mesh.isEnabled()) {
  25799. continue;
  25800. }
  25801. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25802. continue;
  25803. }
  25804. if (!mesh.isReady(true)) {
  25805. return false;
  25806. }
  25807. // Effect layers
  25808. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25809. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25810. var layer = _a[_i];
  25811. if (!layer.hasMesh(mesh)) {
  25812. continue;
  25813. }
  25814. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25815. var subMesh = _c[_b];
  25816. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25817. return false;
  25818. }
  25819. }
  25820. }
  25821. }
  25822. // Post-processes
  25823. if (this.activeCameras && this.activeCameras.length > 0) {
  25824. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25825. var camera = _e[_d];
  25826. if (!camera.isReady(true)) {
  25827. return false;
  25828. }
  25829. }
  25830. }
  25831. else if (this.activeCamera) {
  25832. if (!this.activeCamera.isReady(true)) {
  25833. return false;
  25834. }
  25835. }
  25836. // Particles
  25837. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25838. var particleSystem = _g[_f];
  25839. if (!particleSystem.isReady()) {
  25840. return false;
  25841. }
  25842. }
  25843. return true;
  25844. };
  25845. /** Resets all cached information relative to material (including effect and visibility) */
  25846. Scene.prototype.resetCachedMaterial = function () {
  25847. this._cachedMaterial = null;
  25848. this._cachedEffect = null;
  25849. this._cachedVisibility = null;
  25850. };
  25851. /**
  25852. * Registers a function to be called before every frame render
  25853. * @param func defines the function to register
  25854. */
  25855. Scene.prototype.registerBeforeRender = function (func) {
  25856. this.onBeforeRenderObservable.add(func);
  25857. };
  25858. /**
  25859. * Unregisters a function called before every frame render
  25860. * @param func defines the function to unregister
  25861. */
  25862. Scene.prototype.unregisterBeforeRender = function (func) {
  25863. this.onBeforeRenderObservable.removeCallback(func);
  25864. };
  25865. /**
  25866. * Registers a function to be called after every frame render
  25867. * @param func defines the function to register
  25868. */
  25869. Scene.prototype.registerAfterRender = function (func) {
  25870. this.onAfterRenderObservable.add(func);
  25871. };
  25872. /**
  25873. * Unregisters a function called after every frame render
  25874. * @param func defines the function to unregister
  25875. */
  25876. Scene.prototype.unregisterAfterRender = function (func) {
  25877. this.onAfterRenderObservable.removeCallback(func);
  25878. };
  25879. Scene.prototype._executeOnceBeforeRender = function (func) {
  25880. var _this = this;
  25881. var execFunc = function () {
  25882. func();
  25883. setTimeout(function () {
  25884. _this.unregisterBeforeRender(execFunc);
  25885. });
  25886. };
  25887. this.registerBeforeRender(execFunc);
  25888. };
  25889. /**
  25890. * The provided function will run before render once and will be disposed afterwards.
  25891. * A timeout delay can be provided so that the function will be executed in N ms.
  25892. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25893. * @param func The function to be executed.
  25894. * @param timeout optional delay in ms
  25895. */
  25896. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25897. var _this = this;
  25898. if (timeout !== undefined) {
  25899. setTimeout(function () {
  25900. _this._executeOnceBeforeRender(func);
  25901. }, timeout);
  25902. }
  25903. else {
  25904. this._executeOnceBeforeRender(func);
  25905. }
  25906. };
  25907. /** @hidden */
  25908. Scene.prototype._addPendingData = function (data) {
  25909. this._pendingData.push(data);
  25910. };
  25911. /** @hidden */
  25912. Scene.prototype._removePendingData = function (data) {
  25913. var wasLoading = this.isLoading;
  25914. var index = this._pendingData.indexOf(data);
  25915. if (index !== -1) {
  25916. this._pendingData.splice(index, 1);
  25917. }
  25918. if (wasLoading && !this.isLoading) {
  25919. this.onDataLoadedObservable.notifyObservers(this);
  25920. }
  25921. };
  25922. /**
  25923. * Returns the number of items waiting to be loaded
  25924. * @returns the number of items waiting to be loaded
  25925. */
  25926. Scene.prototype.getWaitingItemsCount = function () {
  25927. return this._pendingData.length;
  25928. };
  25929. Object.defineProperty(Scene.prototype, "isLoading", {
  25930. /**
  25931. * Returns a boolean indicating if the scene is still loading data
  25932. */
  25933. get: function () {
  25934. return this._pendingData.length > 0;
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. /**
  25940. * Registers a function to be executed when the scene is ready
  25941. * @param {Function} func - the function to be executed
  25942. */
  25943. Scene.prototype.executeWhenReady = function (func) {
  25944. var _this = this;
  25945. this.onReadyObservable.add(func);
  25946. if (this._executeWhenReadyTimeoutId !== -1) {
  25947. return;
  25948. }
  25949. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25950. _this._checkIsReady();
  25951. }, 150);
  25952. };
  25953. /**
  25954. * Returns a promise that resolves when the scene is ready
  25955. * @returns A promise that resolves when the scene is ready
  25956. */
  25957. Scene.prototype.whenReadyAsync = function () {
  25958. var _this = this;
  25959. return new Promise(function (resolve) {
  25960. _this.executeWhenReady(function () {
  25961. resolve();
  25962. });
  25963. });
  25964. };
  25965. /** @hidden */
  25966. Scene.prototype._checkIsReady = function () {
  25967. var _this = this;
  25968. if (this.isReady()) {
  25969. this.onReadyObservable.notifyObservers(this);
  25970. this.onReadyObservable.clear();
  25971. this._executeWhenReadyTimeoutId = -1;
  25972. return;
  25973. }
  25974. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25975. _this._checkIsReady();
  25976. }, 150);
  25977. };
  25978. // Animations
  25979. /**
  25980. * Will start the animation sequence of a given target
  25981. * @param target defines the target
  25982. * @param from defines from which frame should animation start
  25983. * @param to defines until which frame should animation run.
  25984. * @param weight defines the weight to apply to the animation (1.0 by default)
  25985. * @param loop defines if the animation loops
  25986. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25987. * @param onAnimationEnd defines the function to be executed when the animation ends
  25988. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25989. * @returns the animatable object created for this animation
  25990. */
  25991. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25992. if (weight === void 0) { weight = 1.0; }
  25993. if (speedRatio === void 0) { speedRatio = 1.0; }
  25994. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25995. returnedAnimatable.weight = weight;
  25996. return returnedAnimatable;
  25997. };
  25998. /**
  25999. * Will start the animation sequence of a given target
  26000. * @param target defines the target
  26001. * @param from defines from which frame should animation start
  26002. * @param to defines until which frame should animation run.
  26003. * @param loop defines if the animation loops
  26004. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26005. * @param onAnimationEnd defines the function to be executed when the animation ends
  26006. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26007. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26008. * @returns the animatable object created for this animation
  26009. */
  26010. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26011. if (speedRatio === void 0) { speedRatio = 1.0; }
  26012. if (stopCurrent === void 0) { stopCurrent = true; }
  26013. if (from > to && speedRatio > 0) {
  26014. speedRatio *= -1;
  26015. }
  26016. if (stopCurrent) {
  26017. this.stopAnimation(target);
  26018. }
  26019. if (!animatable) {
  26020. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26021. }
  26022. // Local animations
  26023. if (target.animations) {
  26024. animatable.appendAnimations(target, target.animations);
  26025. }
  26026. // Children animations
  26027. if (target.getAnimatables) {
  26028. var animatables = target.getAnimatables();
  26029. for (var index = 0; index < animatables.length; index++) {
  26030. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26031. }
  26032. }
  26033. animatable.reset();
  26034. return animatable;
  26035. };
  26036. /**
  26037. * Begin a new animation on a given node
  26038. * @param target defines the target where the animation will take place
  26039. * @param animations defines the list of animations to start
  26040. * @param from defines the initial value
  26041. * @param to defines the final value
  26042. * @param loop defines if you want animation to loop (off by default)
  26043. * @param speedRatio defines the speed ratio to apply to all animations
  26044. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26045. * @returns the list of created animatables
  26046. */
  26047. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26048. if (speedRatio === undefined) {
  26049. speedRatio = 1.0;
  26050. }
  26051. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26052. return animatable;
  26053. };
  26054. /**
  26055. * Begin a new animation on a given node and its hierarchy
  26056. * @param target defines the root node where the animation will take place
  26057. * @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.
  26058. * @param animations defines the list of animations to start
  26059. * @param from defines the initial value
  26060. * @param to defines the final value
  26061. * @param loop defines if you want animation to loop (off by default)
  26062. * @param speedRatio defines the speed ratio to apply to all animations
  26063. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26064. * @returns the list of animatables created for all nodes
  26065. */
  26066. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26067. var children = target.getDescendants(directDescendantsOnly);
  26068. var result = [];
  26069. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26070. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26071. var child = children_1[_i];
  26072. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26073. }
  26074. return result;
  26075. };
  26076. /**
  26077. * Gets the animatable associated with a specific target
  26078. * @param target defines the target of the animatable
  26079. * @returns the required animatable if found
  26080. */
  26081. Scene.prototype.getAnimatableByTarget = function (target) {
  26082. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26083. if (this._activeAnimatables[index].target === target) {
  26084. return this._activeAnimatables[index];
  26085. }
  26086. }
  26087. return null;
  26088. };
  26089. /**
  26090. * Gets all animatables associated with a given target
  26091. * @param target defines the target to look animatables for
  26092. * @returns an array of Animatables
  26093. */
  26094. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26095. var result = [];
  26096. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26097. if (this._activeAnimatables[index].target === target) {
  26098. result.push(this._activeAnimatables[index]);
  26099. }
  26100. }
  26101. return result;
  26102. };
  26103. Object.defineProperty(Scene.prototype, "animatables", {
  26104. /**
  26105. * Gets all animatable attached to the scene
  26106. */
  26107. get: function () {
  26108. return this._activeAnimatables;
  26109. },
  26110. enumerable: true,
  26111. configurable: true
  26112. });
  26113. /**
  26114. * Will stop the animation of the given target
  26115. * @param target - the target
  26116. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26117. */
  26118. Scene.prototype.stopAnimation = function (target, animationName) {
  26119. var animatables = this.getAllAnimatablesByTarget(target);
  26120. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26121. var animatable = animatables_1[_i];
  26122. animatable.stop(animationName);
  26123. }
  26124. };
  26125. /**
  26126. * Stops and removes all animations that have been applied to the scene
  26127. */
  26128. Scene.prototype.stopAllAnimations = function () {
  26129. if (this._activeAnimatables) {
  26130. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26131. this._activeAnimatables[i].stop();
  26132. }
  26133. this._activeAnimatables = [];
  26134. }
  26135. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26136. var group = _a[_i];
  26137. group.stop();
  26138. }
  26139. };
  26140. Scene.prototype._animate = function () {
  26141. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26142. return;
  26143. }
  26144. // Getting time
  26145. var now = BABYLON.Tools.Now;
  26146. if (!this._animationTimeLast) {
  26147. if (this._pendingData.length > 0) {
  26148. return;
  26149. }
  26150. this._animationTimeLast = now;
  26151. }
  26152. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26153. this._animationTime += deltaTime;
  26154. this._animationTimeLast = now;
  26155. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26156. this._activeAnimatables[index]._animate(this._animationTime);
  26157. }
  26158. // Late animation bindings
  26159. this._processLateAnimationBindings();
  26160. };
  26161. /** @hidden */
  26162. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26163. var target = runtimeAnimation.target;
  26164. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26165. if (!target._lateAnimationHolders) {
  26166. target._lateAnimationHolders = {};
  26167. }
  26168. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26169. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26170. totalWeight: 0,
  26171. animations: [],
  26172. originalValue: originalValue
  26173. };
  26174. }
  26175. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26176. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26177. };
  26178. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26179. var normalizer = 1.0;
  26180. var finalPosition = BABYLON.Tmp.Vector3[0];
  26181. var finalScaling = BABYLON.Tmp.Vector3[1];
  26182. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26183. var startIndex = 0;
  26184. var originalAnimation = holder.animations[0];
  26185. var originalValue = holder.originalValue;
  26186. var scale = 1;
  26187. if (holder.totalWeight < 1.0) {
  26188. // We need to mix the original value in
  26189. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26190. scale = 1.0 - holder.totalWeight;
  26191. }
  26192. else {
  26193. startIndex = 1;
  26194. // We need to normalize the weights
  26195. normalizer = holder.totalWeight;
  26196. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26197. scale = originalAnimation.weight / normalizer;
  26198. if (scale == 1) {
  26199. return originalAnimation.currentValue;
  26200. }
  26201. }
  26202. finalScaling.scaleInPlace(scale);
  26203. finalPosition.scaleInPlace(scale);
  26204. finalQuaternion.scaleInPlace(scale);
  26205. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26206. var runtimeAnimation = holder.animations[animIndex];
  26207. var scale = runtimeAnimation.weight / normalizer;
  26208. var currentPosition = BABYLON.Tmp.Vector3[2];
  26209. var currentScaling = BABYLON.Tmp.Vector3[3];
  26210. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26211. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26212. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26213. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26214. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26215. }
  26216. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26217. return originalAnimation._workValue;
  26218. };
  26219. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26220. var originalAnimation = holder.animations[0];
  26221. var originalValue = holder.originalValue;
  26222. if (holder.animations.length === 1) {
  26223. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26224. }
  26225. var normalizer = 1.0;
  26226. var quaternions;
  26227. var weights;
  26228. if (holder.totalWeight < 1.0) {
  26229. var scale = 1.0 - holder.totalWeight;
  26230. quaternions = [];
  26231. weights = [];
  26232. quaternions.push(originalValue);
  26233. weights.push(scale);
  26234. }
  26235. else {
  26236. if (holder.animations.length === 2) { // Slerp as soon as we can
  26237. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26238. }
  26239. quaternions = [];
  26240. weights = [];
  26241. normalizer = holder.totalWeight;
  26242. }
  26243. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26244. var runtimeAnimation = holder.animations[animIndex];
  26245. quaternions.push(runtimeAnimation.currentValue);
  26246. weights.push(runtimeAnimation.weight / normalizer);
  26247. }
  26248. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26249. var cumulativeAmount = 0;
  26250. var cumulativeQuaternion = null;
  26251. for (var index = 0; index < quaternions.length;) {
  26252. if (!cumulativeQuaternion) {
  26253. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26254. cumulativeAmount = weights[index] + weights[index + 1];
  26255. index += 2;
  26256. continue;
  26257. }
  26258. cumulativeAmount += weights[index];
  26259. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26260. index++;
  26261. }
  26262. return cumulativeQuaternion;
  26263. };
  26264. Scene.prototype._processLateAnimationBindings = function () {
  26265. if (!this._registeredForLateAnimationBindings.length) {
  26266. return;
  26267. }
  26268. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26269. var target = this._registeredForLateAnimationBindings.data[index];
  26270. for (var path in target._lateAnimationHolders) {
  26271. var holder = target._lateAnimationHolders[path];
  26272. var originalAnimation = holder.animations[0];
  26273. var originalValue = holder.originalValue;
  26274. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26275. var finalValue = void 0;
  26276. if (matrixDecomposeMode) {
  26277. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26278. }
  26279. else {
  26280. var quaternionMode = originalValue.w !== undefined;
  26281. if (quaternionMode) {
  26282. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26283. }
  26284. else {
  26285. var startIndex = 0;
  26286. var normalizer = 1.0;
  26287. if (holder.totalWeight < 1.0) {
  26288. // We need to mix the original value in
  26289. if (originalValue.scale) {
  26290. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26291. }
  26292. else {
  26293. finalValue = originalValue * (1.0 - holder.totalWeight);
  26294. }
  26295. }
  26296. else {
  26297. // We need to normalize the weights
  26298. normalizer = holder.totalWeight;
  26299. var scale_1 = originalAnimation.weight / normalizer;
  26300. if (scale_1 !== 1) {
  26301. if (originalAnimation.currentValue.scale) {
  26302. finalValue = originalAnimation.currentValue.scale(scale_1);
  26303. }
  26304. else {
  26305. finalValue = originalAnimation.currentValue * scale_1;
  26306. }
  26307. }
  26308. else {
  26309. finalValue = originalAnimation.currentValue;
  26310. }
  26311. startIndex = 1;
  26312. }
  26313. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26314. var runtimeAnimation = holder.animations[animIndex];
  26315. var scale = runtimeAnimation.weight / normalizer;
  26316. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26317. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26318. }
  26319. else {
  26320. finalValue += runtimeAnimation.currentValue * scale;
  26321. }
  26322. }
  26323. }
  26324. }
  26325. target[path] = finalValue;
  26326. }
  26327. target._lateAnimationHolders = {};
  26328. }
  26329. this._registeredForLateAnimationBindings.reset();
  26330. };
  26331. // Matrix
  26332. /** @hidden */
  26333. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26334. this._useAlternateCameraConfiguration = active;
  26335. };
  26336. /**
  26337. * Gets the current view matrix
  26338. * @returns a Matrix
  26339. */
  26340. Scene.prototype.getViewMatrix = function () {
  26341. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26342. };
  26343. /**
  26344. * Gets the current projection matrix
  26345. * @returns a Matrix
  26346. */
  26347. Scene.prototype.getProjectionMatrix = function () {
  26348. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26349. };
  26350. /**
  26351. * Gets the current transform matrix
  26352. * @returns a Matrix made of View * Projection
  26353. */
  26354. Scene.prototype.getTransformMatrix = function () {
  26355. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26356. };
  26357. /**
  26358. * Sets the current transform matrix
  26359. * @param view defines the View matrix to use
  26360. * @param projection defines the Projection matrix to use
  26361. */
  26362. Scene.prototype.setTransformMatrix = function (view, projection) {
  26363. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26364. return;
  26365. }
  26366. this._viewUpdateFlag = view.updateFlag;
  26367. this._projectionUpdateFlag = projection.updateFlag;
  26368. this._viewMatrix = view;
  26369. this._projectionMatrix = projection;
  26370. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26371. // Update frustum
  26372. if (!this._frustumPlanes) {
  26373. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26374. }
  26375. else {
  26376. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26377. }
  26378. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26379. var otherCamera = this.activeCamera._alternateCamera;
  26380. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26381. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26382. }
  26383. if (this._sceneUbo.useUbo) {
  26384. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26385. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26386. this._sceneUbo.update();
  26387. }
  26388. };
  26389. /** @hidden */
  26390. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26391. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26392. return;
  26393. }
  26394. this._alternateViewUpdateFlag = view.updateFlag;
  26395. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26396. this._alternateViewMatrix = view;
  26397. this._alternateProjectionMatrix = projection;
  26398. if (!this._alternateTransformMatrix) {
  26399. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26400. }
  26401. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26402. if (!this._alternateSceneUbo) {
  26403. this._createAlternateUbo();
  26404. }
  26405. if (this._alternateSceneUbo.useUbo) {
  26406. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26407. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26408. this._alternateSceneUbo.update();
  26409. }
  26410. };
  26411. /**
  26412. * Gets the uniform buffer used to store scene data
  26413. * @returns a UniformBuffer
  26414. */
  26415. Scene.prototype.getSceneUniformBuffer = function () {
  26416. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26417. };
  26418. /**
  26419. * Gets an unique (relatively to the current scene) Id
  26420. * @returns an unique number for the scene
  26421. */
  26422. Scene.prototype.getUniqueId = function () {
  26423. var result = Scene._uniqueIdCounter;
  26424. Scene._uniqueIdCounter++;
  26425. return result;
  26426. };
  26427. /**
  26428. * Add a mesh to the list of scene's meshes
  26429. * @param newMesh defines the mesh to add
  26430. * @param recursive if all child meshes should also be added to the scene
  26431. */
  26432. Scene.prototype.addMesh = function (newMesh, recursive) {
  26433. var _this = this;
  26434. if (recursive === void 0) { recursive = false; }
  26435. this.meshes.push(newMesh);
  26436. //notify the collision coordinator
  26437. if (this.collisionCoordinator) {
  26438. this.collisionCoordinator.onMeshAdded(newMesh);
  26439. }
  26440. newMesh._resyncLightSources();
  26441. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26442. if (recursive) {
  26443. newMesh.getChildMeshes().forEach(function (m) {
  26444. _this.addMesh(m);
  26445. });
  26446. }
  26447. };
  26448. /**
  26449. * Remove a mesh for the list of scene's meshes
  26450. * @param toRemove defines the mesh to remove
  26451. * @param recursive if all child meshes should also be removed from the scene
  26452. * @returns the index where the mesh was in the mesh list
  26453. */
  26454. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26455. var _this = this;
  26456. if (recursive === void 0) { recursive = false; }
  26457. var index = this.meshes.indexOf(toRemove);
  26458. if (index !== -1) {
  26459. // Remove from the scene if mesh found
  26460. this.meshes.splice(index, 1);
  26461. }
  26462. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26463. if (recursive) {
  26464. toRemove.getChildMeshes().forEach(function (m) {
  26465. _this.removeMesh(m);
  26466. });
  26467. }
  26468. return index;
  26469. };
  26470. /**
  26471. * Add a transform node to the list of scene's transform nodes
  26472. * @param newTransformNode defines the transform node to add
  26473. */
  26474. Scene.prototype.addTransformNode = function (newTransformNode) {
  26475. this.transformNodes.push(newTransformNode);
  26476. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26477. };
  26478. /**
  26479. * Remove a transform node for the list of scene's transform nodes
  26480. * @param toRemove defines the transform node to remove
  26481. * @returns the index where the transform node was in the transform node list
  26482. */
  26483. Scene.prototype.removeTransformNode = function (toRemove) {
  26484. var index = this.transformNodes.indexOf(toRemove);
  26485. if (index !== -1) {
  26486. // Remove from the scene if found
  26487. this.transformNodes.splice(index, 1);
  26488. }
  26489. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26490. return index;
  26491. };
  26492. /**
  26493. * Remove a skeleton for the list of scene's skeletons
  26494. * @param toRemove defines the skeleton to remove
  26495. * @returns the index where the skeleton was in the skeleton list
  26496. */
  26497. Scene.prototype.removeSkeleton = function (toRemove) {
  26498. var index = this.skeletons.indexOf(toRemove);
  26499. if (index !== -1) {
  26500. // Remove from the scene if found
  26501. this.skeletons.splice(index, 1);
  26502. }
  26503. return index;
  26504. };
  26505. /**
  26506. * Remove a morph target for the list of scene's morph targets
  26507. * @param toRemove defines the morph target to remove
  26508. * @returns the index where the morph target was in the morph target list
  26509. */
  26510. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26511. var index = this.morphTargetManagers.indexOf(toRemove);
  26512. if (index !== -1) {
  26513. // Remove from the scene if found
  26514. this.morphTargetManagers.splice(index, 1);
  26515. }
  26516. return index;
  26517. };
  26518. /**
  26519. * Remove a light for the list of scene's lights
  26520. * @param toRemove defines the light to remove
  26521. * @returns the index where the light was in the light list
  26522. */
  26523. Scene.prototype.removeLight = function (toRemove) {
  26524. var index = this.lights.indexOf(toRemove);
  26525. if (index !== -1) {
  26526. // Remove from meshes
  26527. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26528. var mesh = _a[_i];
  26529. mesh._removeLightSource(toRemove);
  26530. }
  26531. // Remove from the scene if mesh found
  26532. this.lights.splice(index, 1);
  26533. this.sortLightsByPriority();
  26534. }
  26535. this.onLightRemovedObservable.notifyObservers(toRemove);
  26536. return index;
  26537. };
  26538. /**
  26539. * Remove a camera for the list of scene's cameras
  26540. * @param toRemove defines the camera to remove
  26541. * @returns the index where the camera was in the camera list
  26542. */
  26543. Scene.prototype.removeCamera = function (toRemove) {
  26544. var index = this.cameras.indexOf(toRemove);
  26545. if (index !== -1) {
  26546. // Remove from the scene if mesh found
  26547. this.cameras.splice(index, 1);
  26548. }
  26549. // Remove from activeCameras
  26550. var index2 = this.activeCameras.indexOf(toRemove);
  26551. if (index2 !== -1) {
  26552. // Remove from the scene if mesh found
  26553. this.activeCameras.splice(index2, 1);
  26554. }
  26555. // Reset the activeCamera
  26556. if (this.activeCamera === toRemove) {
  26557. if (this.cameras.length > 0) {
  26558. this.activeCamera = this.cameras[0];
  26559. }
  26560. else {
  26561. this.activeCamera = null;
  26562. }
  26563. }
  26564. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26565. return index;
  26566. };
  26567. /**
  26568. * Remove a particle system for the list of scene's particle systems
  26569. * @param toRemove defines the particle system to remove
  26570. * @returns the index where the particle system was in the particle system list
  26571. */
  26572. Scene.prototype.removeParticleSystem = function (toRemove) {
  26573. var index = this.particleSystems.indexOf(toRemove);
  26574. if (index !== -1) {
  26575. this.particleSystems.splice(index, 1);
  26576. }
  26577. return index;
  26578. };
  26579. /**
  26580. * Remove a animation for the list of scene's animations
  26581. * @param toRemove defines the animation to remove
  26582. * @returns the index where the animation was in the animation list
  26583. */
  26584. Scene.prototype.removeAnimation = function (toRemove) {
  26585. var index = this.animations.indexOf(toRemove);
  26586. if (index !== -1) {
  26587. this.animations.splice(index, 1);
  26588. }
  26589. return index;
  26590. };
  26591. /**
  26592. * Removes the given animation group from this scene.
  26593. * @param toRemove The animation group to remove
  26594. * @returns The index of the removed animation group
  26595. */
  26596. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26597. var index = this.animationGroups.indexOf(toRemove);
  26598. if (index !== -1) {
  26599. this.animationGroups.splice(index, 1);
  26600. }
  26601. return index;
  26602. };
  26603. /**
  26604. * Removes the given multi-material from this scene.
  26605. * @param toRemove The multi-material to remove
  26606. * @returns The index of the removed multi-material
  26607. */
  26608. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26609. var index = this.multiMaterials.indexOf(toRemove);
  26610. if (index !== -1) {
  26611. this.multiMaterials.splice(index, 1);
  26612. }
  26613. return index;
  26614. };
  26615. /**
  26616. * Removes the given material from this scene.
  26617. * @param toRemove The material to remove
  26618. * @returns The index of the removed material
  26619. */
  26620. Scene.prototype.removeMaterial = function (toRemove) {
  26621. var index = this.materials.indexOf(toRemove);
  26622. if (index !== -1) {
  26623. this.materials.splice(index, 1);
  26624. }
  26625. return index;
  26626. };
  26627. /**
  26628. * Removes the given lens flare system from this scene.
  26629. * @param toRemove The lens flare system to remove
  26630. * @returns The index of the removed lens flare system
  26631. */
  26632. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26633. var index = this.lensFlareSystems.indexOf(toRemove);
  26634. if (index !== -1) {
  26635. this.lensFlareSystems.splice(index, 1);
  26636. }
  26637. return index;
  26638. };
  26639. /**
  26640. * Removes the given action manager from this scene.
  26641. * @param toRemove The action manager to remove
  26642. * @returns The index of the removed action manager
  26643. */
  26644. Scene.prototype.removeActionManager = function (toRemove) {
  26645. var index = this._actionManagers.indexOf(toRemove);
  26646. if (index !== -1) {
  26647. this._actionManagers.splice(index, 1);
  26648. }
  26649. return index;
  26650. };
  26651. /**
  26652. * Removes the given effect layer from this scene.
  26653. * @param toRemove defines the effect layer to remove
  26654. * @returns the index of the removed effect layer
  26655. */
  26656. Scene.prototype.removeEffectLayer = function (toRemove) {
  26657. var index = this.effectLayers.indexOf(toRemove);
  26658. if (index !== -1) {
  26659. this.effectLayers.splice(index, 1);
  26660. }
  26661. return index;
  26662. };
  26663. /**
  26664. * Removes the given texture from this scene.
  26665. * @param toRemove The texture to remove
  26666. * @returns The index of the removed texture
  26667. */
  26668. Scene.prototype.removeTexture = function (toRemove) {
  26669. var index = this.textures.indexOf(toRemove);
  26670. if (index !== -1) {
  26671. this.textures.splice(index, 1);
  26672. }
  26673. return index;
  26674. };
  26675. /**
  26676. * Adds the given light to this scene
  26677. * @param newLight The light to add
  26678. */
  26679. Scene.prototype.addLight = function (newLight) {
  26680. this.lights.push(newLight);
  26681. this.sortLightsByPriority();
  26682. // Add light to all meshes (To support if the light is removed and then readded)
  26683. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26684. var mesh = _a[_i];
  26685. if (mesh._lightSources.indexOf(newLight) === -1) {
  26686. mesh._lightSources.push(newLight);
  26687. mesh._resyncLightSources();
  26688. }
  26689. }
  26690. this.onNewLightAddedObservable.notifyObservers(newLight);
  26691. };
  26692. /**
  26693. * Sorts the list list based on light priorities
  26694. */
  26695. Scene.prototype.sortLightsByPriority = function () {
  26696. if (this.requireLightSorting) {
  26697. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26698. }
  26699. };
  26700. /**
  26701. * Adds the given camera to this scene
  26702. * @param newCamera The camera to add
  26703. */
  26704. Scene.prototype.addCamera = function (newCamera) {
  26705. this.cameras.push(newCamera);
  26706. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26707. };
  26708. /**
  26709. * Adds the given skeleton to this scene
  26710. * @param newSkeleton The skeleton to add
  26711. */
  26712. Scene.prototype.addSkeleton = function (newSkeleton) {
  26713. this.skeletons.push(newSkeleton);
  26714. };
  26715. /**
  26716. * Adds the given particle system to this scene
  26717. * @param newParticleSystem The particle system to add
  26718. */
  26719. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26720. this.particleSystems.push(newParticleSystem);
  26721. };
  26722. /**
  26723. * Adds the given animation to this scene
  26724. * @param newAnimation The animation to add
  26725. */
  26726. Scene.prototype.addAnimation = function (newAnimation) {
  26727. this.animations.push(newAnimation);
  26728. };
  26729. /**
  26730. * Adds the given animation group to this scene.
  26731. * @param newAnimationGroup The animation group to add
  26732. */
  26733. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26734. this.animationGroups.push(newAnimationGroup);
  26735. };
  26736. /**
  26737. * Adds the given multi-material to this scene
  26738. * @param newMultiMaterial The multi-material to add
  26739. */
  26740. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26741. this.multiMaterials.push(newMultiMaterial);
  26742. };
  26743. /**
  26744. * Adds the given material to this scene
  26745. * @param newMaterial The material to add
  26746. */
  26747. Scene.prototype.addMaterial = function (newMaterial) {
  26748. this.materials.push(newMaterial);
  26749. };
  26750. /**
  26751. * Adds the given morph target to this scene
  26752. * @param newMorphTargetManager The morph target to add
  26753. */
  26754. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26755. this.morphTargetManagers.push(newMorphTargetManager);
  26756. };
  26757. /**
  26758. * Adds the given geometry to this scene
  26759. * @param newGeometry The geometry to add
  26760. */
  26761. Scene.prototype.addGeometry = function (newGeometry) {
  26762. this._geometries.push(newGeometry);
  26763. };
  26764. /**
  26765. * Adds the given lens flare system to this scene
  26766. * @param newLensFlareSystem The lens flare system to add
  26767. */
  26768. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26769. this.lensFlareSystems.push(newLensFlareSystem);
  26770. };
  26771. /**
  26772. * Adds the given effect layer to this scene
  26773. * @param newEffectLayer defines the effect layer to add
  26774. */
  26775. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26776. this.effectLayers.push(newEffectLayer);
  26777. };
  26778. /**
  26779. * Adds the given action manager to this scene
  26780. * @param newActionManager The action manager to add
  26781. */
  26782. Scene.prototype.addActionManager = function (newActionManager) {
  26783. this._actionManagers.push(newActionManager);
  26784. };
  26785. /**
  26786. * Adds the given texture to this scene.
  26787. * @param newTexture The texture to add
  26788. */
  26789. Scene.prototype.addTexture = function (newTexture) {
  26790. this.textures.push(newTexture);
  26791. };
  26792. /**
  26793. * Switch active camera
  26794. * @param newCamera defines the new active camera
  26795. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26796. */
  26797. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26798. if (attachControl === void 0) { attachControl = true; }
  26799. var canvas = this._engine.getRenderingCanvas();
  26800. if (!canvas) {
  26801. return;
  26802. }
  26803. if (this.activeCamera) {
  26804. this.activeCamera.detachControl(canvas);
  26805. }
  26806. this.activeCamera = newCamera;
  26807. if (attachControl) {
  26808. newCamera.attachControl(canvas);
  26809. }
  26810. };
  26811. /**
  26812. * sets the active camera of the scene using its ID
  26813. * @param id defines the camera's ID
  26814. * @return the new active camera or null if none found.
  26815. */
  26816. Scene.prototype.setActiveCameraByID = function (id) {
  26817. var camera = this.getCameraByID(id);
  26818. if (camera) {
  26819. this.activeCamera = camera;
  26820. return camera;
  26821. }
  26822. return null;
  26823. };
  26824. /**
  26825. * sets the active camera of the scene using its name
  26826. * @param name defines the camera's name
  26827. * @returns the new active camera or null if none found.
  26828. */
  26829. Scene.prototype.setActiveCameraByName = function (name) {
  26830. var camera = this.getCameraByName(name);
  26831. if (camera) {
  26832. this.activeCamera = camera;
  26833. return camera;
  26834. }
  26835. return null;
  26836. };
  26837. /**
  26838. * get an animation group using its name
  26839. * @param name defines the material's name
  26840. * @return the animation group or null if none found.
  26841. */
  26842. Scene.prototype.getAnimationGroupByName = function (name) {
  26843. for (var index = 0; index < this.animationGroups.length; index++) {
  26844. if (this.animationGroups[index].name === name) {
  26845. return this.animationGroups[index];
  26846. }
  26847. }
  26848. return null;
  26849. };
  26850. /**
  26851. * get a material using its id
  26852. * @param id defines the material's ID
  26853. * @return the material or null if none found.
  26854. */
  26855. Scene.prototype.getMaterialByID = function (id) {
  26856. for (var index = 0; index < this.materials.length; index++) {
  26857. if (this.materials[index].id === id) {
  26858. return this.materials[index];
  26859. }
  26860. }
  26861. return null;
  26862. };
  26863. /**
  26864. * Gets a material using its name
  26865. * @param name defines the material's name
  26866. * @return the material or null if none found.
  26867. */
  26868. Scene.prototype.getMaterialByName = function (name) {
  26869. for (var index = 0; index < this.materials.length; index++) {
  26870. if (this.materials[index].name === name) {
  26871. return this.materials[index];
  26872. }
  26873. }
  26874. return null;
  26875. };
  26876. /**
  26877. * Gets a lens flare system using its name
  26878. * @param name defines the name to look for
  26879. * @returns the lens flare system or null if not found
  26880. */
  26881. Scene.prototype.getLensFlareSystemByName = function (name) {
  26882. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26883. if (this.lensFlareSystems[index].name === name) {
  26884. return this.lensFlareSystems[index];
  26885. }
  26886. }
  26887. return null;
  26888. };
  26889. /**
  26890. * Gets a lens flare system using its id
  26891. * @param id defines the id to look for
  26892. * @returns the lens flare system or null if not found
  26893. */
  26894. Scene.prototype.getLensFlareSystemByID = function (id) {
  26895. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26896. if (this.lensFlareSystems[index].id === id) {
  26897. return this.lensFlareSystems[index];
  26898. }
  26899. }
  26900. return null;
  26901. };
  26902. /**
  26903. * Gets a camera using its id
  26904. * @param id defines the id to look for
  26905. * @returns the camera or null if not found
  26906. */
  26907. Scene.prototype.getCameraByID = function (id) {
  26908. for (var index = 0; index < this.cameras.length; index++) {
  26909. if (this.cameras[index].id === id) {
  26910. return this.cameras[index];
  26911. }
  26912. }
  26913. return null;
  26914. };
  26915. /**
  26916. * Gets a camera using its unique id
  26917. * @param uniqueId defines the unique id to look for
  26918. * @returns the camera or null if not found
  26919. */
  26920. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26921. for (var index = 0; index < this.cameras.length; index++) {
  26922. if (this.cameras[index].uniqueId === uniqueId) {
  26923. return this.cameras[index];
  26924. }
  26925. }
  26926. return null;
  26927. };
  26928. /**
  26929. * Gets a camera using its name
  26930. * @param name defines the camera's name
  26931. * @return the camera or null if none found.
  26932. */
  26933. Scene.prototype.getCameraByName = function (name) {
  26934. for (var index = 0; index < this.cameras.length; index++) {
  26935. if (this.cameras[index].name === name) {
  26936. return this.cameras[index];
  26937. }
  26938. }
  26939. return null;
  26940. };
  26941. /**
  26942. * Gets a bone using its id
  26943. * @param id defines the bone's id
  26944. * @return the bone or null if not found
  26945. */
  26946. Scene.prototype.getBoneByID = function (id) {
  26947. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26948. var skeleton = this.skeletons[skeletonIndex];
  26949. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26950. if (skeleton.bones[boneIndex].id === id) {
  26951. return skeleton.bones[boneIndex];
  26952. }
  26953. }
  26954. }
  26955. return null;
  26956. };
  26957. /**
  26958. * Gets a bone using its id
  26959. * @param name defines the bone's name
  26960. * @return the bone or null if not found
  26961. */
  26962. Scene.prototype.getBoneByName = function (name) {
  26963. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26964. var skeleton = this.skeletons[skeletonIndex];
  26965. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26966. if (skeleton.bones[boneIndex].name === name) {
  26967. return skeleton.bones[boneIndex];
  26968. }
  26969. }
  26970. }
  26971. return null;
  26972. };
  26973. /**
  26974. * Gets a light node using its name
  26975. * @param name defines the the light's name
  26976. * @return the light or null if none found.
  26977. */
  26978. Scene.prototype.getLightByName = function (name) {
  26979. for (var index = 0; index < this.lights.length; index++) {
  26980. if (this.lights[index].name === name) {
  26981. return this.lights[index];
  26982. }
  26983. }
  26984. return null;
  26985. };
  26986. /**
  26987. * Gets a light node using its id
  26988. * @param id defines the light's id
  26989. * @return the light or null if none found.
  26990. */
  26991. Scene.prototype.getLightByID = function (id) {
  26992. for (var index = 0; index < this.lights.length; index++) {
  26993. if (this.lights[index].id === id) {
  26994. return this.lights[index];
  26995. }
  26996. }
  26997. return null;
  26998. };
  26999. /**
  27000. * Gets a light node using its scene-generated unique ID
  27001. * @param uniqueId defines the light's unique id
  27002. * @return the light or null if none found.
  27003. */
  27004. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27005. for (var index = 0; index < this.lights.length; index++) {
  27006. if (this.lights[index].uniqueId === uniqueId) {
  27007. return this.lights[index];
  27008. }
  27009. }
  27010. return null;
  27011. };
  27012. /**
  27013. * Gets a particle system by id
  27014. * @param id defines the particle system id
  27015. * @return the corresponding system or null if none found
  27016. */
  27017. Scene.prototype.getParticleSystemByID = function (id) {
  27018. for (var index = 0; index < this.particleSystems.length; index++) {
  27019. if (this.particleSystems[index].id === id) {
  27020. return this.particleSystems[index];
  27021. }
  27022. }
  27023. return null;
  27024. };
  27025. /**
  27026. * Gets a geometry using its ID
  27027. * @param id defines the geometry's id
  27028. * @return the geometry or null if none found.
  27029. */
  27030. Scene.prototype.getGeometryByID = function (id) {
  27031. for (var index = 0; index < this._geometries.length; index++) {
  27032. if (this._geometries[index].id === id) {
  27033. return this._geometries[index];
  27034. }
  27035. }
  27036. return null;
  27037. };
  27038. /**
  27039. * Add a new geometry to this scene
  27040. * @param geometry defines the geometry to be added to the scene.
  27041. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27042. * @return a boolean defining if the geometry was added or not
  27043. */
  27044. Scene.prototype.pushGeometry = function (geometry, force) {
  27045. if (!force && this.getGeometryByID(geometry.id)) {
  27046. return false;
  27047. }
  27048. this._geometries.push(geometry);
  27049. //notify the collision coordinator
  27050. if (this.collisionCoordinator) {
  27051. this.collisionCoordinator.onGeometryAdded(geometry);
  27052. }
  27053. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27054. return true;
  27055. };
  27056. /**
  27057. * Removes an existing geometry
  27058. * @param geometry defines the geometry to be removed from the scene
  27059. * @return a boolean defining if the geometry was removed or not
  27060. */
  27061. Scene.prototype.removeGeometry = function (geometry) {
  27062. var index = this._geometries.indexOf(geometry);
  27063. if (index > -1) {
  27064. this._geometries.splice(index, 1);
  27065. //notify the collision coordinator
  27066. if (this.collisionCoordinator) {
  27067. this.collisionCoordinator.onGeometryDeleted(geometry);
  27068. }
  27069. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27070. return true;
  27071. }
  27072. return false;
  27073. };
  27074. /**
  27075. * Gets the list of geometries attached to the scene
  27076. * @returns an array of Geometry
  27077. */
  27078. Scene.prototype.getGeometries = function () {
  27079. return this._geometries;
  27080. };
  27081. /**
  27082. * Gets the first added mesh found of a given ID
  27083. * @param id defines the id to search for
  27084. * @return the mesh found or null if not found at all
  27085. */
  27086. Scene.prototype.getMeshByID = function (id) {
  27087. for (var index = 0; index < this.meshes.length; index++) {
  27088. if (this.meshes[index].id === id) {
  27089. return this.meshes[index];
  27090. }
  27091. }
  27092. return null;
  27093. };
  27094. /**
  27095. * Gets a list of meshes using their id
  27096. * @param id defines the id to search for
  27097. * @returns a list of meshes
  27098. */
  27099. Scene.prototype.getMeshesByID = function (id) {
  27100. return this.meshes.filter(function (m) {
  27101. return m.id === id;
  27102. });
  27103. };
  27104. /**
  27105. * Gets the first added transform node found of a given ID
  27106. * @param id defines the id to search for
  27107. * @return the found transform node or null if not found at all.
  27108. */
  27109. Scene.prototype.getTransformNodeByID = function (id) {
  27110. for (var index = 0; index < this.transformNodes.length; index++) {
  27111. if (this.transformNodes[index].id === id) {
  27112. return this.transformNodes[index];
  27113. }
  27114. }
  27115. return null;
  27116. };
  27117. /**
  27118. * Gets a list of transform nodes using their id
  27119. * @param id defines the id to search for
  27120. * @returns a list of transform nodes
  27121. */
  27122. Scene.prototype.getTransformNodesByID = function (id) {
  27123. return this.transformNodes.filter(function (m) {
  27124. return m.id === id;
  27125. });
  27126. };
  27127. /**
  27128. * Gets a mesh with its auto-generated unique id
  27129. * @param uniqueId defines the unique id to search for
  27130. * @return the found mesh or null if not found at all.
  27131. */
  27132. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27133. for (var index = 0; index < this.meshes.length; index++) {
  27134. if (this.meshes[index].uniqueId === uniqueId) {
  27135. return this.meshes[index];
  27136. }
  27137. }
  27138. return null;
  27139. };
  27140. /**
  27141. * Gets a the last added mesh using a given id
  27142. * @param id defines the id to search for
  27143. * @return the found mesh or null if not found at all.
  27144. */
  27145. Scene.prototype.getLastMeshByID = function (id) {
  27146. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27147. if (this.meshes[index].id === id) {
  27148. return this.meshes[index];
  27149. }
  27150. }
  27151. return null;
  27152. };
  27153. /**
  27154. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27155. * @param id defines the id to search for
  27156. * @return the found node or null if not found at all
  27157. */
  27158. Scene.prototype.getLastEntryByID = function (id) {
  27159. var index;
  27160. for (index = this.meshes.length - 1; index >= 0; index--) {
  27161. if (this.meshes[index].id === id) {
  27162. return this.meshes[index];
  27163. }
  27164. }
  27165. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27166. if (this.transformNodes[index].id === id) {
  27167. return this.transformNodes[index];
  27168. }
  27169. }
  27170. for (index = this.cameras.length - 1; index >= 0; index--) {
  27171. if (this.cameras[index].id === id) {
  27172. return this.cameras[index];
  27173. }
  27174. }
  27175. for (index = this.lights.length - 1; index >= 0; index--) {
  27176. if (this.lights[index].id === id) {
  27177. return this.lights[index];
  27178. }
  27179. }
  27180. return null;
  27181. };
  27182. /**
  27183. * Gets a node (Mesh, Camera, Light) using a given id
  27184. * @param id defines the id to search for
  27185. * @return the found node or null if not found at all
  27186. */
  27187. Scene.prototype.getNodeByID = function (id) {
  27188. var mesh = this.getMeshByID(id);
  27189. if (mesh) {
  27190. return mesh;
  27191. }
  27192. var light = this.getLightByID(id);
  27193. if (light) {
  27194. return light;
  27195. }
  27196. var camera = this.getCameraByID(id);
  27197. if (camera) {
  27198. return camera;
  27199. }
  27200. var bone = this.getBoneByID(id);
  27201. return bone;
  27202. };
  27203. /**
  27204. * Gets a node (Mesh, Camera, Light) using a given name
  27205. * @param name defines the name to search for
  27206. * @return the found node or null if not found at all.
  27207. */
  27208. Scene.prototype.getNodeByName = function (name) {
  27209. var mesh = this.getMeshByName(name);
  27210. if (mesh) {
  27211. return mesh;
  27212. }
  27213. var light = this.getLightByName(name);
  27214. if (light) {
  27215. return light;
  27216. }
  27217. var camera = this.getCameraByName(name);
  27218. if (camera) {
  27219. return camera;
  27220. }
  27221. var bone = this.getBoneByName(name);
  27222. return bone;
  27223. };
  27224. /**
  27225. * Gets a mesh using a given name
  27226. * @param name defines the name to search for
  27227. * @return the found mesh or null if not found at all.
  27228. */
  27229. Scene.prototype.getMeshByName = function (name) {
  27230. for (var index = 0; index < this.meshes.length; index++) {
  27231. if (this.meshes[index].name === name) {
  27232. return this.meshes[index];
  27233. }
  27234. }
  27235. return null;
  27236. };
  27237. /**
  27238. * Gets a transform node using a given name
  27239. * @param name defines the name to search for
  27240. * @return the found transform node or null if not found at all.
  27241. */
  27242. Scene.prototype.getTransformNodeByName = function (name) {
  27243. for (var index = 0; index < this.transformNodes.length; index++) {
  27244. if (this.transformNodes[index].name === name) {
  27245. return this.transformNodes[index];
  27246. }
  27247. }
  27248. return null;
  27249. };
  27250. /**
  27251. * Gets a sound using a given name
  27252. * @param name defines the name to search for
  27253. * @return the found sound or null if not found at all.
  27254. */
  27255. Scene.prototype.getSoundByName = function (name) {
  27256. var index;
  27257. if (BABYLON.AudioEngine) {
  27258. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27259. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27260. return this.mainSoundTrack.soundCollection[index];
  27261. }
  27262. }
  27263. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27264. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27265. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27266. return this.soundTracks[sdIndex].soundCollection[index];
  27267. }
  27268. }
  27269. }
  27270. }
  27271. return null;
  27272. };
  27273. /**
  27274. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27275. * @param id defines the id to search for
  27276. * @return the found skeleton or null if not found at all.
  27277. */
  27278. Scene.prototype.getLastSkeletonByID = function (id) {
  27279. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27280. if (this.skeletons[index].id === id) {
  27281. return this.skeletons[index];
  27282. }
  27283. }
  27284. return null;
  27285. };
  27286. /**
  27287. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27288. * @param id defines the id to search for
  27289. * @return the found skeleton or null if not found at all.
  27290. */
  27291. Scene.prototype.getSkeletonById = function (id) {
  27292. for (var index = 0; index < this.skeletons.length; index++) {
  27293. if (this.skeletons[index].id === id) {
  27294. return this.skeletons[index];
  27295. }
  27296. }
  27297. return null;
  27298. };
  27299. /**
  27300. * Gets a skeleton using a given name
  27301. * @param name defines the name to search for
  27302. * @return the found skeleton or null if not found at all.
  27303. */
  27304. Scene.prototype.getSkeletonByName = function (name) {
  27305. for (var index = 0; index < this.skeletons.length; index++) {
  27306. if (this.skeletons[index].name === name) {
  27307. return this.skeletons[index];
  27308. }
  27309. }
  27310. return null;
  27311. };
  27312. /**
  27313. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27314. * @param id defines the id to search for
  27315. * @return the found morph target manager or null if not found at all.
  27316. */
  27317. Scene.prototype.getMorphTargetManagerById = function (id) {
  27318. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27319. if (this.morphTargetManagers[index].uniqueId === id) {
  27320. return this.morphTargetManagers[index];
  27321. }
  27322. }
  27323. return null;
  27324. };
  27325. /**
  27326. * Gets a boolean indicating if the given mesh is active
  27327. * @param mesh defines the mesh to look for
  27328. * @returns true if the mesh is in the active list
  27329. */
  27330. Scene.prototype.isActiveMesh = function (mesh) {
  27331. return (this._activeMeshes.indexOf(mesh) !== -1);
  27332. };
  27333. /**
  27334. * Return a the first highlight layer of the scene with a given name.
  27335. * @param name The name of the highlight layer to look for.
  27336. * @return The highlight layer if found otherwise null.
  27337. */
  27338. Scene.prototype.getHighlightLayerByName = function (name) {
  27339. for (var index = 0; index < this.effectLayers.length; index++) {
  27340. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27341. return this.effectLayers[index];
  27342. }
  27343. }
  27344. return null;
  27345. };
  27346. /**
  27347. * Return a the first highlight layer of the scene with a given name.
  27348. * @param name The name of the highlight layer to look for.
  27349. * @return The highlight layer if found otherwise null.
  27350. */
  27351. Scene.prototype.getGlowLayerByName = function (name) {
  27352. for (var index = 0; index < this.effectLayers.length; index++) {
  27353. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27354. return this.effectLayers[index];
  27355. }
  27356. }
  27357. return null;
  27358. };
  27359. Object.defineProperty(Scene.prototype, "uid", {
  27360. /**
  27361. * Return a unique id as a string which can serve as an identifier for the scene
  27362. */
  27363. get: function () {
  27364. if (!this._uid) {
  27365. this._uid = BABYLON.Tools.RandomId();
  27366. }
  27367. return this._uid;
  27368. },
  27369. enumerable: true,
  27370. configurable: true
  27371. });
  27372. /**
  27373. * Add an externaly attached data from its key.
  27374. * This method call will fail and return false, if such key already exists.
  27375. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27376. * @param key the unique key that identifies the data
  27377. * @param data the data object to associate to the key for this Engine instance
  27378. * @return true if no such key were already present and the data was added successfully, false otherwise
  27379. */
  27380. Scene.prototype.addExternalData = function (key, data) {
  27381. if (!this._externalData) {
  27382. this._externalData = new BABYLON.StringDictionary();
  27383. }
  27384. return this._externalData.add(key, data);
  27385. };
  27386. /**
  27387. * Get an externaly attached data from its key
  27388. * @param key the unique key that identifies the data
  27389. * @return the associated data, if present (can be null), or undefined if not present
  27390. */
  27391. Scene.prototype.getExternalData = function (key) {
  27392. if (!this._externalData) {
  27393. return null;
  27394. }
  27395. return this._externalData.get(key);
  27396. };
  27397. /**
  27398. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27399. * @param key the unique key that identifies the data
  27400. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27401. * @return the associated data, can be null if the factory returned null.
  27402. */
  27403. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27404. if (!this._externalData) {
  27405. this._externalData = new BABYLON.StringDictionary();
  27406. }
  27407. return this._externalData.getOrAddWithFactory(key, factory);
  27408. };
  27409. /**
  27410. * Remove an externaly attached data from the Engine instance
  27411. * @param key the unique key that identifies the data
  27412. * @return true if the data was successfully removed, false if it doesn't exist
  27413. */
  27414. Scene.prototype.removeExternalData = function (key) {
  27415. return this._externalData.remove(key);
  27416. };
  27417. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27418. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27419. if (mesh.showSubMeshesBoundingBox) {
  27420. var boundingInfo = subMesh.getBoundingInfo();
  27421. if (boundingInfo !== null && boundingInfo !== undefined) {
  27422. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27423. }
  27424. }
  27425. var material = subMesh.getMaterial();
  27426. if (material !== null && material !== undefined) {
  27427. // Render targets
  27428. if (material.getRenderTargetTextures !== undefined) {
  27429. if (this._processedMaterials.indexOf(material) === -1) {
  27430. this._processedMaterials.push(material);
  27431. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27432. }
  27433. }
  27434. // Dispatch
  27435. this._activeIndices.addCount(subMesh.indexCount, false);
  27436. this._renderingManager.dispatch(subMesh, mesh, material);
  27437. }
  27438. }
  27439. };
  27440. /**
  27441. * Clear the processed materials smart array preventing retention point in material dispose.
  27442. */
  27443. Scene.prototype.freeProcessedMaterials = function () {
  27444. this._processedMaterials.dispose();
  27445. };
  27446. /**
  27447. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27448. */
  27449. Scene.prototype.freeActiveMeshes = function () {
  27450. this._activeMeshes.dispose();
  27451. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27452. this.activeCamera._activeMeshes.dispose();
  27453. }
  27454. if (this.activeCameras) {
  27455. for (var i = 0; i < this.activeCameras.length; i++) {
  27456. var activeCamera = this.activeCameras[i];
  27457. if (activeCamera && activeCamera._activeMeshes) {
  27458. activeCamera._activeMeshes.dispose();
  27459. }
  27460. }
  27461. }
  27462. };
  27463. /**
  27464. * Clear the info related to rendering groups preventing retention points during dispose.
  27465. */
  27466. Scene.prototype.freeRenderingGroups = function () {
  27467. if (this._renderingManager) {
  27468. this._renderingManager.freeRenderingGroups();
  27469. }
  27470. if (this.textures) {
  27471. for (var i = 0; i < this.textures.length; i++) {
  27472. var texture = this.textures[i];
  27473. if (texture && texture.renderList) {
  27474. texture.freeRenderingGroups();
  27475. }
  27476. }
  27477. }
  27478. };
  27479. /** @hidden */
  27480. Scene.prototype._isInIntermediateRendering = function () {
  27481. return this._intermediateRendering;
  27482. };
  27483. /**
  27484. * Defines the current active mesh candidate provider
  27485. * @param provider defines the provider to use
  27486. */
  27487. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27488. this._activeMeshCandidateProvider = provider;
  27489. };
  27490. /**
  27491. * Gets the current active mesh candidate provider
  27492. * @returns the current active mesh candidate provider
  27493. */
  27494. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27495. return this._activeMeshCandidateProvider;
  27496. };
  27497. /**
  27498. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27499. * @returns the current scene
  27500. */
  27501. Scene.prototype.freezeActiveMeshes = function () {
  27502. if (!this.activeCamera) {
  27503. return this;
  27504. }
  27505. if (!this._frustumPlanes) {
  27506. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27507. }
  27508. this._evaluateActiveMeshes();
  27509. this._activeMeshesFrozen = true;
  27510. return this;
  27511. };
  27512. /**
  27513. * Use this function to restart evaluating active meshes on every frame
  27514. * @returns the current scene
  27515. */
  27516. Scene.prototype.unfreezeActiveMeshes = function () {
  27517. this._activeMeshesFrozen = false;
  27518. return this;
  27519. };
  27520. Scene.prototype._evaluateActiveMeshes = function () {
  27521. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27522. return;
  27523. }
  27524. if (!this.activeCamera) {
  27525. return;
  27526. }
  27527. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27528. this.activeCamera._activeMeshes.reset();
  27529. this._activeMeshes.reset();
  27530. this._renderingManager.reset();
  27531. this._processedMaterials.reset();
  27532. this._activeParticleSystems.reset();
  27533. this._activeSkeletons.reset();
  27534. this._softwareSkinnedMeshes.reset();
  27535. if (this._boundingBoxRenderer) {
  27536. this._boundingBoxRenderer.reset();
  27537. }
  27538. // Meshes
  27539. var meshes;
  27540. var len;
  27541. var checkIsEnabled = true;
  27542. // Determine mesh candidates
  27543. if (this._activeMeshCandidateProvider !== undefined) {
  27544. // Use _activeMeshCandidateProvider
  27545. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27546. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27547. if (meshes !== undefined) {
  27548. len = meshes.length;
  27549. }
  27550. else {
  27551. len = 0;
  27552. }
  27553. }
  27554. else if (this._selectionOctree !== undefined) {
  27555. // Octree
  27556. var selection = this._selectionOctree.select(this._frustumPlanes);
  27557. meshes = selection.data;
  27558. len = selection.length;
  27559. }
  27560. else {
  27561. // Full scene traversal
  27562. len = this.meshes.length;
  27563. meshes = this.meshes;
  27564. }
  27565. // Check each mesh
  27566. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27567. mesh = meshes[meshIndex];
  27568. if (mesh.isBlocked) {
  27569. continue;
  27570. }
  27571. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27572. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27573. continue;
  27574. }
  27575. mesh.computeWorldMatrix();
  27576. // Intersections
  27577. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27578. this._meshesForIntersections.pushNoDuplicate(mesh);
  27579. }
  27580. // Switch to current LOD
  27581. meshLOD = mesh.getLOD(this.activeCamera);
  27582. if (meshLOD === undefined || meshLOD === null) {
  27583. continue;
  27584. }
  27585. mesh._preActivate();
  27586. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27587. this._activeMeshes.push(mesh);
  27588. this.activeCamera._activeMeshes.push(mesh);
  27589. mesh._activate(this._renderId);
  27590. if (meshLOD !== mesh) {
  27591. meshLOD._activate(this._renderId);
  27592. }
  27593. this._activeMesh(mesh, meshLOD);
  27594. }
  27595. }
  27596. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27597. // Particle systems
  27598. if (this.particlesEnabled) {
  27599. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27600. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27601. var particleSystem = this.particleSystems[particleIndex];
  27602. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27603. continue;
  27604. }
  27605. var emitter = particleSystem.emitter;
  27606. if (!emitter.position || emitter.isEnabled()) {
  27607. this._activeParticleSystems.push(particleSystem);
  27608. particleSystem.animate();
  27609. this._renderingManager.dispatchParticles(particleSystem);
  27610. }
  27611. }
  27612. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27613. }
  27614. };
  27615. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27616. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27617. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27618. mesh.skeleton.prepare();
  27619. }
  27620. if (!mesh.computeBonesUsingShaders) {
  27621. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27622. }
  27623. }
  27624. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27625. var boundingInfo = sourceMesh.getBoundingInfo();
  27626. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27627. }
  27628. if (mesh !== undefined && mesh !== null
  27629. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27630. // Submeshes Octrees
  27631. var len;
  27632. var subMeshes;
  27633. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27634. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27635. len = intersections.length;
  27636. subMeshes = intersections.data;
  27637. }
  27638. else {
  27639. subMeshes = mesh.subMeshes;
  27640. len = subMeshes.length;
  27641. }
  27642. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27643. subMesh = subMeshes[subIndex];
  27644. this._evaluateSubMesh(subMesh, mesh);
  27645. }
  27646. }
  27647. };
  27648. /**
  27649. * Update the transform matrix to update from the current active camera
  27650. * @param force defines a boolean used to force the update even if cache is up to date
  27651. */
  27652. Scene.prototype.updateTransformMatrix = function (force) {
  27653. if (!this.activeCamera) {
  27654. return;
  27655. }
  27656. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27657. };
  27658. /**
  27659. * 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)
  27660. * @param alternateCamera defines the camera to use
  27661. */
  27662. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27663. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27664. };
  27665. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27666. if (camera && camera._skipRendering) {
  27667. return;
  27668. }
  27669. var engine = this._engine;
  27670. this.activeCamera = camera;
  27671. if (!this.activeCamera)
  27672. throw new Error("Active camera not set");
  27673. // Viewport
  27674. engine.setViewport(this.activeCamera.viewport);
  27675. // Camera
  27676. this.resetCachedMaterial();
  27677. this._renderId++;
  27678. this.updateTransformMatrix();
  27679. if (camera._alternateCamera) {
  27680. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27681. this._alternateRendering = true;
  27682. }
  27683. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27684. // Meshes
  27685. this._evaluateActiveMeshes();
  27686. // Software skinning
  27687. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27688. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27689. mesh.applySkeleton(mesh.skeleton);
  27690. }
  27691. // Render targets
  27692. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27693. var needsRestoreFrameBuffer = false;
  27694. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27695. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27696. }
  27697. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27698. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27699. }
  27700. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27701. this._intermediateRendering = true;
  27702. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27703. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27704. var renderTarget = this._renderTargets.data[renderIndex];
  27705. if (renderTarget._shouldRender()) {
  27706. this._renderId++;
  27707. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27708. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27709. }
  27710. }
  27711. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27712. this._intermediateRendering = false;
  27713. this._renderId++;
  27714. needsRestoreFrameBuffer = true; // Restore back buffer
  27715. }
  27716. // Render EffectLayer Texture
  27717. var stencilState = this._engine.getStencilBuffer();
  27718. var renderEffects = false;
  27719. var needStencil = false;
  27720. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27721. this._intermediateRendering = true;
  27722. for (var i = 0; i < this.effectLayers.length; i++) {
  27723. var effectLayer = this.effectLayers[i];
  27724. if (effectLayer.shouldRender() &&
  27725. (!effectLayer.camera ||
  27726. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27727. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27728. renderEffects = true;
  27729. needStencil = needStencil || effectLayer.needStencil();
  27730. var renderTarget = effectLayer._mainTexture;
  27731. if (renderTarget._shouldRender()) {
  27732. this._renderId++;
  27733. renderTarget.render(false, false);
  27734. needsRestoreFrameBuffer = true;
  27735. }
  27736. }
  27737. }
  27738. this._intermediateRendering = false;
  27739. this._renderId++;
  27740. }
  27741. if (needsRestoreFrameBuffer) {
  27742. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27743. }
  27744. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27745. // Prepare Frame
  27746. if (this.postProcessManager) {
  27747. this.postProcessManager._prepareFrame();
  27748. }
  27749. // Backgrounds
  27750. var layerIndex;
  27751. var layer;
  27752. if (this.layers.length) {
  27753. engine.setDepthBuffer(false);
  27754. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27755. layer = this.layers[layerIndex];
  27756. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27757. layer.render();
  27758. }
  27759. }
  27760. engine.setDepthBuffer(true);
  27761. }
  27762. // Activate effect Layer stencil
  27763. if (needStencil) {
  27764. this._engine.setStencilBuffer(true);
  27765. }
  27766. // Render
  27767. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27768. this._renderingManager.render(null, null, true, true);
  27769. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27770. // Restore effect Layer stencil
  27771. if (needStencil) {
  27772. this._engine.setStencilBuffer(stencilState);
  27773. }
  27774. // Bounding boxes
  27775. if (this._boundingBoxRenderer) {
  27776. this._boundingBoxRenderer.render();
  27777. }
  27778. // Lens flares
  27779. if (this.lensFlaresEnabled) {
  27780. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27781. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27782. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27783. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27784. lensFlareSystem.render();
  27785. }
  27786. }
  27787. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27788. }
  27789. // Effect Layer
  27790. if (renderEffects) {
  27791. engine.setDepthBuffer(false);
  27792. for (var i = 0; i < this.effectLayers.length; i++) {
  27793. if (this.effectLayers[i].shouldRender()) {
  27794. this.effectLayers[i].render();
  27795. }
  27796. }
  27797. engine.setDepthBuffer(true);
  27798. }
  27799. // Foregrounds
  27800. if (this.layers.length) {
  27801. engine.setDepthBuffer(false);
  27802. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27803. layer = this.layers[layerIndex];
  27804. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27805. layer.render();
  27806. }
  27807. }
  27808. engine.setDepthBuffer(true);
  27809. }
  27810. // Finalize frame
  27811. if (this.postProcessManager) {
  27812. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27813. }
  27814. // Reset some special arrays
  27815. this._renderTargets.reset();
  27816. this._alternateRendering = false;
  27817. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27818. };
  27819. Scene.prototype._processSubCameras = function (camera) {
  27820. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27821. this._renderForCamera(camera);
  27822. return;
  27823. }
  27824. // rig cameras
  27825. for (var index = 0; index < camera._rigCameras.length; index++) {
  27826. this._renderForCamera(camera._rigCameras[index], camera);
  27827. }
  27828. this.activeCamera = camera;
  27829. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27830. };
  27831. Scene.prototype._checkIntersections = function () {
  27832. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27833. var sourceMesh = this._meshesForIntersections.data[index];
  27834. if (!sourceMesh.actionManager) {
  27835. continue;
  27836. }
  27837. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27838. var action = sourceMesh.actionManager.actions[actionIndex];
  27839. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27840. var parameters = action.getTriggerParameter();
  27841. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27842. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27843. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27844. if (areIntersecting && currentIntersectionInProgress === -1) {
  27845. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27846. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27847. sourceMesh._intersectionsInProgress.push(otherMesh);
  27848. }
  27849. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27850. sourceMesh._intersectionsInProgress.push(otherMesh);
  27851. }
  27852. }
  27853. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27854. //They intersected, and now they don't.
  27855. //is this trigger an exit trigger? execute an event.
  27856. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27857. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27858. }
  27859. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27860. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27861. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27862. return otherMesh === parameterMesh;
  27863. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27864. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27865. }
  27866. }
  27867. }
  27868. }
  27869. }
  27870. };
  27871. /**
  27872. * Render the scene
  27873. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27874. */
  27875. Scene.prototype.render = function (updateCameras) {
  27876. if (updateCameras === void 0) { updateCameras = true; }
  27877. if (this.isDisposed) {
  27878. return;
  27879. }
  27880. this._activeParticles.fetchNewFrame();
  27881. this._totalVertices.fetchNewFrame();
  27882. this._activeIndices.fetchNewFrame();
  27883. this._activeBones.fetchNewFrame();
  27884. this._meshesForIntersections.reset();
  27885. this.resetCachedMaterial();
  27886. this.onBeforeAnimationsObservable.notifyObservers(this);
  27887. // Actions
  27888. if (this.actionManager) {
  27889. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27890. }
  27891. //Simplification Queue
  27892. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27893. this.simplificationQueue.executeNext();
  27894. }
  27895. if (this._engine.isDeterministicLockStep()) {
  27896. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27897. var defaultFPS = (60.0 / 1000.0);
  27898. var defaultFrameTime = 1000 / 60; // frame time in MS
  27899. if (this._physicsEngine) {
  27900. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27901. }
  27902. var stepsTaken = 0;
  27903. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27904. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27905. internalSteps = Math.min(internalSteps, maxSubSteps);
  27906. do {
  27907. this.onBeforeStepObservable.notifyObservers(this);
  27908. // Animations
  27909. this._animationRatio = defaultFrameTime * defaultFPS;
  27910. this._animate();
  27911. this.onAfterAnimationsObservable.notifyObservers(this);
  27912. // Physics
  27913. if (this._physicsEngine) {
  27914. this.onBeforePhysicsObservable.notifyObservers(this);
  27915. this._physicsEngine._step(defaultFrameTime / 1000);
  27916. this.onAfterPhysicsObservable.notifyObservers(this);
  27917. }
  27918. this.onAfterStepObservable.notifyObservers(this);
  27919. this._currentStepId++;
  27920. stepsTaken++;
  27921. deltaTime -= defaultFrameTime;
  27922. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27923. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27924. }
  27925. else {
  27926. // Animations
  27927. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27928. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27929. this._animate();
  27930. this.onAfterAnimationsObservable.notifyObservers(this);
  27931. // Physics
  27932. if (this._physicsEngine) {
  27933. this.onBeforePhysicsObservable.notifyObservers(this);
  27934. this._physicsEngine._step(deltaTime / 1000.0);
  27935. this.onAfterPhysicsObservable.notifyObservers(this);
  27936. }
  27937. }
  27938. // update gamepad manager
  27939. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27940. this._gamepadManager._checkGamepadsStatus();
  27941. }
  27942. // Update Cameras
  27943. if (updateCameras) {
  27944. if (this.activeCameras.length > 0) {
  27945. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27946. var camera = this.activeCameras[cameraIndex];
  27947. camera.update();
  27948. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27949. // rig cameras
  27950. for (var index = 0; index < camera._rigCameras.length; index++) {
  27951. camera._rigCameras[index].update();
  27952. }
  27953. }
  27954. }
  27955. }
  27956. else if (this.activeCamera) {
  27957. this.activeCamera.update();
  27958. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27959. // rig cameras
  27960. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27961. this.activeCamera._rigCameras[index].update();
  27962. }
  27963. }
  27964. }
  27965. }
  27966. // Before render
  27967. this.onBeforeRenderObservable.notifyObservers(this);
  27968. // Customs render targets
  27969. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27970. var engine = this.getEngine();
  27971. var currentActiveCamera = this.activeCamera;
  27972. if (this.renderTargetsEnabled) {
  27973. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27974. this._intermediateRendering = true;
  27975. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27976. var renderTarget = this.customRenderTargets[customIndex];
  27977. if (renderTarget._shouldRender()) {
  27978. this._renderId++;
  27979. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27980. if (!this.activeCamera)
  27981. throw new Error("Active camera not set");
  27982. // Viewport
  27983. engine.setViewport(this.activeCamera.viewport);
  27984. // Camera
  27985. this.updateTransformMatrix();
  27986. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27987. }
  27988. }
  27989. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27990. this._intermediateRendering = false;
  27991. this._renderId++;
  27992. }
  27993. // Restore back buffer
  27994. if (this.customRenderTargets.length > 0) {
  27995. engine.restoreDefaultFramebuffer();
  27996. }
  27997. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27998. this.activeCamera = currentActiveCamera;
  27999. // Procedural textures
  28000. if (this.proceduralTexturesEnabled) {
  28001. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28002. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28003. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28004. if (proceduralTexture._shouldRender()) {
  28005. proceduralTexture.render();
  28006. }
  28007. }
  28008. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28009. }
  28010. // Clear
  28011. if (this.autoClearDepthAndStencil || this.autoClear) {
  28012. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28013. }
  28014. // Shadows
  28015. if (this.shadowsEnabled) {
  28016. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28017. var light = this.lights[lightIndex];
  28018. var shadowGenerator = light.getShadowGenerator();
  28019. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28020. var shadowMap = (shadowGenerator.getShadowMap());
  28021. if (this.textures.indexOf(shadowMap) !== -1) {
  28022. this._renderTargets.push(shadowMap);
  28023. }
  28024. }
  28025. }
  28026. }
  28027. // Depth renderer
  28028. for (var key in this._depthRenderer) {
  28029. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28030. }
  28031. // Geometry renderer
  28032. if (this._geometryBufferRenderer) {
  28033. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28034. }
  28035. // RenderPipeline
  28036. if (this._postProcessRenderPipelineManager) {
  28037. this._postProcessRenderPipelineManager.update();
  28038. }
  28039. // Multi-cameras?
  28040. if (this.activeCameras.length > 0) {
  28041. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28042. if (cameraIndex > 0) {
  28043. this._engine.clear(null, false, true, true);
  28044. }
  28045. this._processSubCameras(this.activeCameras[cameraIndex]);
  28046. }
  28047. }
  28048. else {
  28049. if (!this.activeCamera) {
  28050. throw new Error("No camera defined");
  28051. }
  28052. this._processSubCameras(this.activeCamera);
  28053. }
  28054. // Intersection checks
  28055. this._checkIntersections();
  28056. // Update the audio listener attached to the camera
  28057. if (BABYLON.AudioEngine) {
  28058. this._updateAudioParameters();
  28059. }
  28060. // After render
  28061. if (this.afterRender) {
  28062. this.afterRender();
  28063. }
  28064. this.onAfterRenderObservable.notifyObservers(this);
  28065. // Cleaning
  28066. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28067. var data = this._toBeDisposed.data[index];
  28068. if (data) {
  28069. data.dispose();
  28070. }
  28071. this._toBeDisposed[index] = null;
  28072. }
  28073. this._toBeDisposed.reset();
  28074. if (this.dumpNextRenderTargets) {
  28075. this.dumpNextRenderTargets = false;
  28076. }
  28077. this._activeBones.addCount(0, true);
  28078. this._activeIndices.addCount(0, true);
  28079. this._activeParticles.addCount(0, true);
  28080. };
  28081. Scene.prototype._updateAudioParameters = function () {
  28082. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28083. return;
  28084. }
  28085. var listeningCamera;
  28086. var audioEngine = BABYLON.Engine.audioEngine;
  28087. if (this.activeCameras.length > 0) {
  28088. listeningCamera = this.activeCameras[0];
  28089. }
  28090. else {
  28091. listeningCamera = this.activeCamera;
  28092. }
  28093. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28094. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28095. // for VR cameras
  28096. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28097. listeningCamera = listeningCamera.rigCameras[0];
  28098. }
  28099. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28100. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28101. cameraDirection.normalize();
  28102. // To avoid some errors on GearVR
  28103. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28104. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28105. }
  28106. var i;
  28107. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28108. var sound = this.mainSoundTrack.soundCollection[i];
  28109. if (sound.useCustomAttenuation) {
  28110. sound.updateDistanceFromListener();
  28111. }
  28112. }
  28113. for (i = 0; i < this.soundTracks.length; i++) {
  28114. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28115. sound = this.soundTracks[i].soundCollection[j];
  28116. if (sound.useCustomAttenuation) {
  28117. sound.updateDistanceFromListener();
  28118. }
  28119. }
  28120. }
  28121. }
  28122. };
  28123. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28124. // Audio
  28125. /**
  28126. * Gets or sets if audio support is enabled
  28127. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28128. */
  28129. get: function () {
  28130. return this._audioEnabled;
  28131. },
  28132. set: function (value) {
  28133. this._audioEnabled = value;
  28134. if (BABYLON.AudioEngine) {
  28135. if (this._audioEnabled) {
  28136. this._enableAudio();
  28137. }
  28138. else {
  28139. this._disableAudio();
  28140. }
  28141. }
  28142. },
  28143. enumerable: true,
  28144. configurable: true
  28145. });
  28146. Scene.prototype._disableAudio = function () {
  28147. var i;
  28148. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28149. this.mainSoundTrack.soundCollection[i].pause();
  28150. }
  28151. for (i = 0; i < this.soundTracks.length; i++) {
  28152. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28153. this.soundTracks[i].soundCollection[j].pause();
  28154. }
  28155. }
  28156. };
  28157. Scene.prototype._enableAudio = function () {
  28158. var i;
  28159. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28160. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28161. this.mainSoundTrack.soundCollection[i].play();
  28162. }
  28163. }
  28164. for (i = 0; i < this.soundTracks.length; i++) {
  28165. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28166. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28167. this.soundTracks[i].soundCollection[j].play();
  28168. }
  28169. }
  28170. }
  28171. };
  28172. Object.defineProperty(Scene.prototype, "headphone", {
  28173. /**
  28174. * Gets or sets if audio will be output to headphones
  28175. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28176. */
  28177. get: function () {
  28178. return this._headphone;
  28179. },
  28180. set: function (value) {
  28181. this._headphone = value;
  28182. if (BABYLON.AudioEngine) {
  28183. if (this._headphone) {
  28184. this._switchAudioModeForHeadphones();
  28185. }
  28186. else {
  28187. this._switchAudioModeForNormalSpeakers();
  28188. }
  28189. }
  28190. },
  28191. enumerable: true,
  28192. configurable: true
  28193. });
  28194. Scene.prototype._switchAudioModeForHeadphones = function () {
  28195. this.mainSoundTrack.switchPanningModelToHRTF();
  28196. for (var i = 0; i < this.soundTracks.length; i++) {
  28197. this.soundTracks[i].switchPanningModelToHRTF();
  28198. }
  28199. };
  28200. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28201. this.mainSoundTrack.switchPanningModelToEqualPower();
  28202. for (var i = 0; i < this.soundTracks.length; i++) {
  28203. this.soundTracks[i].switchPanningModelToEqualPower();
  28204. }
  28205. };
  28206. /**
  28207. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28208. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28209. * @returns the created depth renderer
  28210. */
  28211. Scene.prototype.enableDepthRenderer = function (camera) {
  28212. camera = camera || this.activeCamera;
  28213. if (!camera) {
  28214. throw "No camera available to enable depth renderer";
  28215. }
  28216. if (!this._depthRenderer[camera.id]) {
  28217. var textureType = 0;
  28218. if (this._engine.getCaps().textureHalfFloatRender) {
  28219. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28220. }
  28221. else if (this._engine.getCaps().textureFloatRender) {
  28222. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28223. }
  28224. else {
  28225. throw "Depth renderer does not support int texture type";
  28226. }
  28227. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28228. }
  28229. return this._depthRenderer[camera.id];
  28230. };
  28231. /**
  28232. * Disables a depth renderer for a given camera
  28233. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28234. */
  28235. Scene.prototype.disableDepthRenderer = function (camera) {
  28236. camera = camera || this.activeCamera;
  28237. if (!camera || !this._depthRenderer[camera.id]) {
  28238. return;
  28239. }
  28240. this._depthRenderer[camera.id].dispose();
  28241. delete this._depthRenderer[camera.id];
  28242. };
  28243. /**
  28244. * Enables a GeometryBufferRender and associates it with the scene
  28245. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28246. * @returns the GeometryBufferRenderer
  28247. */
  28248. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28249. if (ratio === void 0) { ratio = 1; }
  28250. if (this._geometryBufferRenderer) {
  28251. return this._geometryBufferRenderer;
  28252. }
  28253. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28254. if (!this._geometryBufferRenderer.isSupported) {
  28255. this._geometryBufferRenderer = null;
  28256. }
  28257. return this._geometryBufferRenderer;
  28258. };
  28259. /**
  28260. * Disables the GeometryBufferRender associated with the scene
  28261. */
  28262. Scene.prototype.disableGeometryBufferRenderer = function () {
  28263. if (!this._geometryBufferRenderer) {
  28264. return;
  28265. }
  28266. this._geometryBufferRenderer.dispose();
  28267. this._geometryBufferRenderer = null;
  28268. };
  28269. /**
  28270. * Freeze all materials
  28271. * A frozen material will not be updatable but should be faster to render
  28272. */
  28273. Scene.prototype.freezeMaterials = function () {
  28274. for (var i = 0; i < this.materials.length; i++) {
  28275. this.materials[i].freeze();
  28276. }
  28277. };
  28278. /**
  28279. * Unfreeze all materials
  28280. * A frozen material will not be updatable but should be faster to render
  28281. */
  28282. Scene.prototype.unfreezeMaterials = function () {
  28283. for (var i = 0; i < this.materials.length; i++) {
  28284. this.materials[i].unfreeze();
  28285. }
  28286. };
  28287. /**
  28288. * Releases all held ressources
  28289. */
  28290. Scene.prototype.dispose = function () {
  28291. this.beforeRender = null;
  28292. this.afterRender = null;
  28293. this.skeletons = [];
  28294. this.morphTargetManagers = [];
  28295. this.importedMeshesFiles = new Array();
  28296. this.stopAllAnimations();
  28297. this.resetCachedMaterial();
  28298. for (var key in this._depthRenderer) {
  28299. this._depthRenderer[key].dispose();
  28300. }
  28301. if (this._gamepadManager) {
  28302. this._gamepadManager.dispose();
  28303. this._gamepadManager = null;
  28304. }
  28305. // Smart arrays
  28306. if (this.activeCamera) {
  28307. this.activeCamera._activeMeshes.dispose();
  28308. this.activeCamera = null;
  28309. }
  28310. this._activeMeshes.dispose();
  28311. this._renderingManager.dispose();
  28312. this._processedMaterials.dispose();
  28313. this._activeParticleSystems.dispose();
  28314. this._activeSkeletons.dispose();
  28315. this._softwareSkinnedMeshes.dispose();
  28316. this._renderTargets.dispose();
  28317. this._registeredForLateAnimationBindings.dispose();
  28318. if (this._boundingBoxRenderer) {
  28319. this._boundingBoxRenderer.dispose();
  28320. }
  28321. this._meshesForIntersections.dispose();
  28322. this._toBeDisposed.dispose();
  28323. // Abort active requests
  28324. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28325. var request = _a[_i];
  28326. request.abort();
  28327. }
  28328. // Debug layer
  28329. if (this._debugLayer) {
  28330. this._debugLayer.hide();
  28331. }
  28332. // Events
  28333. this.onDisposeObservable.notifyObservers(this);
  28334. this.onDisposeObservable.clear();
  28335. this.onBeforeRenderObservable.clear();
  28336. this.onAfterRenderObservable.clear();
  28337. this.onBeforeRenderTargetsRenderObservable.clear();
  28338. this.onAfterRenderTargetsRenderObservable.clear();
  28339. this.onAfterStepObservable.clear();
  28340. this.onBeforeStepObservable.clear();
  28341. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28342. this.onAfterActiveMeshesEvaluationObservable.clear();
  28343. this.onBeforeParticlesRenderingObservable.clear();
  28344. this.onAfterParticlesRenderingObservable.clear();
  28345. this.onBeforeSpritesRenderingObservable.clear();
  28346. this.onAfterSpritesRenderingObservable.clear();
  28347. this.onBeforeDrawPhaseObservable.clear();
  28348. this.onAfterDrawPhaseObservable.clear();
  28349. this.onBeforePhysicsObservable.clear();
  28350. this.onAfterPhysicsObservable.clear();
  28351. this.onBeforeAnimationsObservable.clear();
  28352. this.onAfterAnimationsObservable.clear();
  28353. this.onDataLoadedObservable.clear();
  28354. this.detachControl();
  28355. // Release sounds & sounds tracks
  28356. if (BABYLON.AudioEngine) {
  28357. this.disposeSounds();
  28358. }
  28359. // VR Helper
  28360. if (this.VRHelper) {
  28361. this.VRHelper.dispose();
  28362. }
  28363. // Detach cameras
  28364. var canvas = this._engine.getRenderingCanvas();
  28365. if (canvas) {
  28366. var index;
  28367. for (index = 0; index < this.cameras.length; index++) {
  28368. this.cameras[index].detachControl(canvas);
  28369. }
  28370. }
  28371. // Release animation groups
  28372. while (this.animationGroups.length) {
  28373. this.animationGroups[0].dispose();
  28374. }
  28375. // Release lights
  28376. while (this.lights.length) {
  28377. this.lights[0].dispose();
  28378. }
  28379. // Release meshes
  28380. while (this.meshes.length) {
  28381. this.meshes[0].dispose(true);
  28382. }
  28383. while (this.transformNodes.length) {
  28384. this.removeTransformNode(this.transformNodes[0]);
  28385. }
  28386. // Release cameras
  28387. while (this.cameras.length) {
  28388. this.cameras[0].dispose();
  28389. }
  28390. // Release materials
  28391. if (this.defaultMaterial) {
  28392. this.defaultMaterial.dispose();
  28393. }
  28394. while (this.multiMaterials.length) {
  28395. this.multiMaterials[0].dispose();
  28396. }
  28397. while (this.materials.length) {
  28398. this.materials[0].dispose();
  28399. }
  28400. // Release particles
  28401. while (this.particleSystems.length) {
  28402. this.particleSystems[0].dispose();
  28403. }
  28404. // Release sprites
  28405. while (this.spriteManagers.length) {
  28406. this.spriteManagers[0].dispose();
  28407. }
  28408. // Release postProcesses
  28409. while (this.postProcesses.length) {
  28410. this.postProcesses[0].dispose();
  28411. }
  28412. // Release layers
  28413. while (this.layers.length) {
  28414. this.layers[0].dispose();
  28415. }
  28416. while (this.effectLayers.length) {
  28417. this.effectLayers[0].dispose();
  28418. }
  28419. // Release textures
  28420. while (this.textures.length) {
  28421. this.textures[0].dispose();
  28422. }
  28423. // Release UBO
  28424. this._sceneUbo.dispose();
  28425. if (this._alternateSceneUbo) {
  28426. this._alternateSceneUbo.dispose();
  28427. }
  28428. // Post-processes
  28429. this.postProcessManager.dispose();
  28430. if (this._postProcessRenderPipelineManager) {
  28431. this._postProcessRenderPipelineManager.dispose();
  28432. }
  28433. // Physics
  28434. if (this._physicsEngine) {
  28435. this.disablePhysicsEngine();
  28436. }
  28437. // Remove from engine
  28438. index = this._engine.scenes.indexOf(this);
  28439. if (index > -1) {
  28440. this._engine.scenes.splice(index, 1);
  28441. }
  28442. this._engine.wipeCaches(true);
  28443. this._isDisposed = true;
  28444. };
  28445. Object.defineProperty(Scene.prototype, "isDisposed", {
  28446. /**
  28447. * Gets if the scene is already disposed
  28448. */
  28449. get: function () {
  28450. return this._isDisposed;
  28451. },
  28452. enumerable: true,
  28453. configurable: true
  28454. });
  28455. /**
  28456. * Releases sounds & soundtracks
  28457. */
  28458. Scene.prototype.disposeSounds = function () {
  28459. if (!this._mainSoundTrack) {
  28460. return;
  28461. }
  28462. this.mainSoundTrack.dispose();
  28463. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28464. this.soundTracks[scIndex].dispose();
  28465. }
  28466. };
  28467. /**
  28468. * Call this function to reduce memory footprint of the scene.
  28469. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28470. */
  28471. Scene.prototype.clearCachedVertexData = function () {
  28472. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28473. var mesh = this.meshes[meshIndex];
  28474. var geometry = mesh.geometry;
  28475. if (geometry) {
  28476. geometry._indices = [];
  28477. for (var vbName in geometry._vertexBuffers) {
  28478. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28479. continue;
  28480. }
  28481. geometry._vertexBuffers[vbName]._buffer._data = null;
  28482. }
  28483. }
  28484. }
  28485. };
  28486. /**
  28487. * This function will remove the local cached buffer data from texture.
  28488. * It will save memory but will prevent the texture from being rebuilt
  28489. */
  28490. Scene.prototype.cleanCachedTextureBuffer = function () {
  28491. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28492. var baseTexture = _a[_i];
  28493. var buffer = baseTexture._buffer;
  28494. if (buffer) {
  28495. baseTexture._buffer = null;
  28496. }
  28497. }
  28498. };
  28499. // Octrees
  28500. /**
  28501. * Get the world extend vectors with an optional filter
  28502. *
  28503. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28504. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28505. */
  28506. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28507. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28508. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28509. filterPredicate = filterPredicate || (function () { return true; });
  28510. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28511. mesh.computeWorldMatrix(true);
  28512. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28513. return;
  28514. }
  28515. var boundingInfo = mesh.getBoundingInfo();
  28516. var minBox = boundingInfo.boundingBox.minimumWorld;
  28517. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28518. BABYLON.Tools.CheckExtends(minBox, min, max);
  28519. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28520. });
  28521. return {
  28522. min: min,
  28523. max: max
  28524. };
  28525. };
  28526. /**
  28527. * Creates or updates the octree used to boost selection (picking)
  28528. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28529. * @param maxCapacity defines the maximum capacity per leaf
  28530. * @param maxDepth defines the maximum depth of the octree
  28531. * @returns an octree of AbstractMesh
  28532. */
  28533. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28534. if (maxCapacity === void 0) { maxCapacity = 64; }
  28535. if (maxDepth === void 0) { maxDepth = 2; }
  28536. if (!this._selectionOctree) {
  28537. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28538. }
  28539. var worldExtends = this.getWorldExtends();
  28540. // Update octree
  28541. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28542. return this._selectionOctree;
  28543. };
  28544. // Picking
  28545. /**
  28546. * Creates a ray that can be used to pick in the scene
  28547. * @param x defines the x coordinate of the origin (on-screen)
  28548. * @param y defines the y coordinate of the origin (on-screen)
  28549. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28550. * @param camera defines the camera to use for the picking
  28551. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28552. * @returns a Ray
  28553. */
  28554. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28555. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28556. var result = BABYLON.Ray.Zero();
  28557. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28558. return result;
  28559. };
  28560. /**
  28561. * Creates a ray that can be used to pick in the scene
  28562. * @param x defines the x coordinate of the origin (on-screen)
  28563. * @param y defines the y coordinate of the origin (on-screen)
  28564. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28565. * @param result defines the ray where to store the picking ray
  28566. * @param camera defines the camera to use for the picking
  28567. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28568. * @returns the current scene
  28569. */
  28570. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28571. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28572. var engine = this._engine;
  28573. if (!camera) {
  28574. if (!this.activeCamera)
  28575. throw new Error("Active camera not set");
  28576. camera = this.activeCamera;
  28577. }
  28578. var cameraViewport = camera.viewport;
  28579. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28580. // Moving coordinates to local viewport world
  28581. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28582. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28583. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28584. return this;
  28585. };
  28586. /**
  28587. * Creates a ray that can be used to pick in the scene
  28588. * @param x defines the x coordinate of the origin (on-screen)
  28589. * @param y defines the y coordinate of the origin (on-screen)
  28590. * @param camera defines the camera to use for the picking
  28591. * @returns a Ray
  28592. */
  28593. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28594. var result = BABYLON.Ray.Zero();
  28595. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28596. return result;
  28597. };
  28598. /**
  28599. * Creates a ray that can be used to pick in the scene
  28600. * @param x defines the x coordinate of the origin (on-screen)
  28601. * @param y defines the y coordinate of the origin (on-screen)
  28602. * @param result defines the ray where to store the picking ray
  28603. * @param camera defines the camera to use for the picking
  28604. * @returns the current scene
  28605. */
  28606. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28607. if (!BABYLON.PickingInfo) {
  28608. return this;
  28609. }
  28610. var engine = this._engine;
  28611. if (!camera) {
  28612. if (!this.activeCamera)
  28613. throw new Error("Active camera not set");
  28614. camera = this.activeCamera;
  28615. }
  28616. var cameraViewport = camera.viewport;
  28617. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28618. var identity = BABYLON.Matrix.Identity();
  28619. // Moving coordinates to local viewport world
  28620. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28621. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28622. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28623. return this;
  28624. };
  28625. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28626. if (!BABYLON.PickingInfo) {
  28627. return null;
  28628. }
  28629. var pickingInfo = null;
  28630. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28631. var mesh = this.meshes[meshIndex];
  28632. if (predicate) {
  28633. if (!predicate(mesh)) {
  28634. continue;
  28635. }
  28636. }
  28637. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28638. continue;
  28639. }
  28640. var world = mesh.getWorldMatrix();
  28641. var ray = rayFunction(world);
  28642. var result = mesh.intersects(ray, fastCheck);
  28643. if (!result || !result.hit)
  28644. continue;
  28645. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28646. continue;
  28647. pickingInfo = result;
  28648. if (fastCheck) {
  28649. break;
  28650. }
  28651. }
  28652. return pickingInfo || new BABYLON.PickingInfo();
  28653. };
  28654. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28655. if (!BABYLON.PickingInfo) {
  28656. return null;
  28657. }
  28658. var pickingInfos = new Array();
  28659. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28660. var mesh = this.meshes[meshIndex];
  28661. if (predicate) {
  28662. if (!predicate(mesh)) {
  28663. continue;
  28664. }
  28665. }
  28666. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28667. continue;
  28668. }
  28669. var world = mesh.getWorldMatrix();
  28670. var ray = rayFunction(world);
  28671. var result = mesh.intersects(ray, false);
  28672. if (!result || !result.hit)
  28673. continue;
  28674. pickingInfos.push(result);
  28675. }
  28676. return pickingInfos;
  28677. };
  28678. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28679. if (!BABYLON.PickingInfo) {
  28680. return null;
  28681. }
  28682. var pickingInfo = null;
  28683. if (!camera) {
  28684. if (!this.activeCamera) {
  28685. return null;
  28686. }
  28687. camera = this.activeCamera;
  28688. }
  28689. if (this.spriteManagers.length > 0) {
  28690. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28691. var spriteManager = this.spriteManagers[spriteIndex];
  28692. if (!spriteManager.isPickable) {
  28693. continue;
  28694. }
  28695. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28696. if (!result || !result.hit)
  28697. continue;
  28698. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28699. continue;
  28700. pickingInfo = result;
  28701. if (fastCheck) {
  28702. break;
  28703. }
  28704. }
  28705. }
  28706. return pickingInfo || new BABYLON.PickingInfo();
  28707. };
  28708. /** Launch a ray to try to pick a mesh in the scene
  28709. * @param x position on screen
  28710. * @param y position on screen
  28711. * @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
  28712. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28713. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28714. * @returns a PickingInfo
  28715. */
  28716. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28717. var _this = this;
  28718. if (!BABYLON.PickingInfo) {
  28719. return null;
  28720. }
  28721. var result = this._internalPick(function (world) {
  28722. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28723. return _this._tempPickingRay;
  28724. }, predicate, fastCheck);
  28725. if (result) {
  28726. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28727. }
  28728. return result;
  28729. };
  28730. /** Launch a ray to try to pick a sprite in the scene
  28731. * @param x position on screen
  28732. * @param y position on screen
  28733. * @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
  28734. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28735. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28736. * @returns a PickingInfo
  28737. */
  28738. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28739. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28740. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28741. };
  28742. /** Use the given ray to pick a mesh in the scene
  28743. * @param ray The ray to use to pick meshes
  28744. * @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
  28745. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28746. * @returns a PickingInfo
  28747. */
  28748. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28749. var _this = this;
  28750. var result = this._internalPick(function (world) {
  28751. if (!_this._pickWithRayInverseMatrix) {
  28752. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28753. }
  28754. world.invertToRef(_this._pickWithRayInverseMatrix);
  28755. if (!_this._cachedRayForTransform) {
  28756. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28757. }
  28758. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28759. return _this._cachedRayForTransform;
  28760. }, predicate, fastCheck);
  28761. if (result) {
  28762. result.ray = ray;
  28763. }
  28764. return result;
  28765. };
  28766. /**
  28767. * Launch a ray to try to pick a mesh in the scene
  28768. * @param x X position on screen
  28769. * @param y Y position on screen
  28770. * @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
  28771. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28772. * @returns an array of PickingInfo
  28773. */
  28774. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28775. var _this = this;
  28776. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28777. };
  28778. /**
  28779. * Launch a ray to try to pick a mesh in the scene
  28780. * @param ray Ray to use
  28781. * @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
  28782. * @returns an array of PickingInfo
  28783. */
  28784. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28785. var _this = this;
  28786. return this._internalMultiPick(function (world) {
  28787. if (!_this._pickWithRayInverseMatrix) {
  28788. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28789. }
  28790. world.invertToRef(_this._pickWithRayInverseMatrix);
  28791. if (!_this._cachedRayForTransform) {
  28792. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28793. }
  28794. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28795. return _this._cachedRayForTransform;
  28796. }, predicate);
  28797. };
  28798. /**
  28799. * Force the value of meshUnderPointer
  28800. * @param mesh defines the mesh to use
  28801. */
  28802. Scene.prototype.setPointerOverMesh = function (mesh) {
  28803. if (this._pointerOverMesh === mesh) {
  28804. return;
  28805. }
  28806. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28807. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28808. }
  28809. this._pointerOverMesh = mesh;
  28810. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28811. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28812. }
  28813. };
  28814. /**
  28815. * Gets the mesh under the pointer
  28816. * @returns a Mesh or null if no mesh is under the pointer
  28817. */
  28818. Scene.prototype.getPointerOverMesh = function () {
  28819. return this._pointerOverMesh;
  28820. };
  28821. /**
  28822. * Force the sprite under the pointer
  28823. * @param sprite defines the sprite to use
  28824. */
  28825. Scene.prototype.setPointerOverSprite = function (sprite) {
  28826. if (this._pointerOverSprite === sprite) {
  28827. return;
  28828. }
  28829. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28830. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28831. }
  28832. this._pointerOverSprite = sprite;
  28833. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28834. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28835. }
  28836. };
  28837. /**
  28838. * Gets the sprite under the pointer
  28839. * @returns a Sprite or null if no sprite is under the pointer
  28840. */
  28841. Scene.prototype.getPointerOverSprite = function () {
  28842. return this._pointerOverSprite;
  28843. };
  28844. // Physics
  28845. /**
  28846. * Gets the current physics engine
  28847. * @returns a PhysicsEngine or null if none attached
  28848. */
  28849. Scene.prototype.getPhysicsEngine = function () {
  28850. return this._physicsEngine;
  28851. };
  28852. /**
  28853. * Enables physics to the current scene
  28854. * @param gravity defines the scene's gravity for the physics engine
  28855. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28856. * @return a boolean indicating if the physics engine was initialized
  28857. */
  28858. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28859. if (gravity === void 0) { gravity = null; }
  28860. if (this._physicsEngine) {
  28861. return true;
  28862. }
  28863. try {
  28864. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28865. return true;
  28866. }
  28867. catch (e) {
  28868. BABYLON.Tools.Error(e.message);
  28869. return false;
  28870. }
  28871. };
  28872. /**
  28873. * Disables and disposes the physics engine associated with the scene
  28874. */
  28875. Scene.prototype.disablePhysicsEngine = function () {
  28876. if (!this._physicsEngine) {
  28877. return;
  28878. }
  28879. this._physicsEngine.dispose();
  28880. this._physicsEngine = null;
  28881. };
  28882. /**
  28883. * Gets a boolean indicating if there is an active physics engine
  28884. * @returns a boolean indicating if there is an active physics engine
  28885. */
  28886. Scene.prototype.isPhysicsEnabled = function () {
  28887. return this._physicsEngine !== undefined;
  28888. };
  28889. /**
  28890. * Deletes a physics compound impostor
  28891. * @param compound defines the compound to delete
  28892. */
  28893. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28894. var mesh = compound.parts[0].mesh;
  28895. if (mesh.physicsImpostor) {
  28896. mesh.physicsImpostor.dispose( /*true*/);
  28897. mesh.physicsImpostor = null;
  28898. }
  28899. };
  28900. // Misc.
  28901. /** @hidden */
  28902. Scene.prototype._rebuildGeometries = function () {
  28903. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28904. var geometry = _a[_i];
  28905. geometry._rebuild();
  28906. }
  28907. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28908. var mesh = _c[_b];
  28909. mesh._rebuild();
  28910. }
  28911. if (this.postProcessManager) {
  28912. this.postProcessManager._rebuild();
  28913. }
  28914. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28915. var layer = _e[_d];
  28916. layer._rebuild();
  28917. }
  28918. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28919. var effectLayer = _g[_f];
  28920. effectLayer._rebuild();
  28921. }
  28922. if (this._boundingBoxRenderer) {
  28923. this._boundingBoxRenderer._rebuild();
  28924. }
  28925. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28926. var system = _j[_h];
  28927. system.rebuild();
  28928. }
  28929. if (this._postProcessRenderPipelineManager) {
  28930. this._postProcessRenderPipelineManager._rebuild();
  28931. }
  28932. };
  28933. /** @hidden */
  28934. Scene.prototype._rebuildTextures = function () {
  28935. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28936. var texture = _a[_i];
  28937. texture._rebuild();
  28938. }
  28939. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28940. };
  28941. /**
  28942. * Creates a default light for the scene.
  28943. * @param replace Whether to replace the existing lights in the scene.
  28944. */
  28945. Scene.prototype.createDefaultLight = function (replace) {
  28946. if (replace === void 0) { replace = false; }
  28947. // Dispose existing light in replace mode.
  28948. if (replace) {
  28949. if (this.lights) {
  28950. for (var i = 0; i < this.lights.length; i++) {
  28951. this.lights[i].dispose();
  28952. }
  28953. }
  28954. }
  28955. // Light
  28956. if (this.lights.length === 0) {
  28957. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28958. }
  28959. };
  28960. /**
  28961. * Creates a default camera for the scene.
  28962. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28963. * @param replace Whether to replace the existing active camera in the scene.
  28964. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28965. */
  28966. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28967. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28968. if (replace === void 0) { replace = false; }
  28969. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28970. // Dispose existing camera in replace mode.
  28971. if (replace) {
  28972. if (this.activeCamera) {
  28973. this.activeCamera.dispose();
  28974. this.activeCamera = null;
  28975. }
  28976. }
  28977. // Camera
  28978. if (!this.activeCamera) {
  28979. var worldExtends = this.getWorldExtends();
  28980. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28981. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28982. var camera;
  28983. var radius = worldSize.length() * 1.5;
  28984. // empty scene scenario!
  28985. if (!isFinite(radius)) {
  28986. radius = 1;
  28987. worldCenter.copyFromFloats(0, 0, 0);
  28988. }
  28989. if (createArcRotateCamera) {
  28990. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28991. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28992. arcRotateCamera.wheelPrecision = 100 / radius;
  28993. camera = arcRotateCamera;
  28994. }
  28995. else {
  28996. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28997. freeCamera.setTarget(worldCenter);
  28998. camera = freeCamera;
  28999. }
  29000. camera.minZ = radius * 0.01;
  29001. camera.maxZ = radius * 1000;
  29002. camera.speed = radius * 0.2;
  29003. this.activeCamera = camera;
  29004. var canvas = this.getEngine().getRenderingCanvas();
  29005. if (attachCameraControls && canvas) {
  29006. camera.attachControl(canvas);
  29007. }
  29008. }
  29009. };
  29010. /**
  29011. * Creates a default camera and a default light
  29012. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29013. * @param replace defines if the camera and/or light will replace the existing ones
  29014. * @param attachCameraControls defines if attachControl will be called on the new camera
  29015. */
  29016. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29017. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29018. if (replace === void 0) { replace = false; }
  29019. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29020. this.createDefaultLight(replace);
  29021. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29022. };
  29023. /**
  29024. * Creates a new sky box
  29025. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29026. * @param environmentTexture defines the texture to use as environment texture
  29027. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29028. * @param scale defines the overall scale of the skybox
  29029. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29030. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29031. * @returns a new mesh holding the sky box
  29032. */
  29033. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29034. if (pbr === void 0) { pbr = false; }
  29035. if (scale === void 0) { scale = 1000; }
  29036. if (blur === void 0) { blur = 0; }
  29037. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29038. if (!environmentTexture) {
  29039. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29040. return null;
  29041. }
  29042. if (setGlobalEnvTexture) {
  29043. if (environmentTexture) {
  29044. this.environmentTexture = environmentTexture;
  29045. }
  29046. }
  29047. // Skybox
  29048. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29049. if (pbr) {
  29050. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29051. hdrSkyboxMaterial.backFaceCulling = false;
  29052. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29053. if (hdrSkyboxMaterial.reflectionTexture) {
  29054. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29055. }
  29056. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29057. hdrSkyboxMaterial.disableLighting = true;
  29058. hdrSkyboxMaterial.twoSidedLighting = true;
  29059. hdrSkybox.infiniteDistance = true;
  29060. hdrSkybox.material = hdrSkyboxMaterial;
  29061. }
  29062. else {
  29063. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29064. skyboxMaterial.backFaceCulling = false;
  29065. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29066. if (skyboxMaterial.reflectionTexture) {
  29067. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29068. }
  29069. skyboxMaterial.disableLighting = true;
  29070. hdrSkybox.infiniteDistance = true;
  29071. hdrSkybox.material = skyboxMaterial;
  29072. }
  29073. return hdrSkybox;
  29074. };
  29075. /**
  29076. * Creates a new environment
  29077. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29078. * @param options defines the options you can use to configure the environment
  29079. * @returns the new EnvironmentHelper
  29080. */
  29081. Scene.prototype.createDefaultEnvironment = function (options) {
  29082. if (BABYLON.EnvironmentHelper) {
  29083. return new BABYLON.EnvironmentHelper(options, this);
  29084. }
  29085. return null;
  29086. };
  29087. /**
  29088. * Creates a new VREXperienceHelper
  29089. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29090. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29091. * @returns a new VREXperienceHelper
  29092. */
  29093. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29094. if (webVROptions === void 0) { webVROptions = {}; }
  29095. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29096. };
  29097. // Tags
  29098. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29099. if (tagsQuery === undefined) {
  29100. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29101. return list;
  29102. }
  29103. var listByTags = [];
  29104. forEach = forEach || (function (item) { return; });
  29105. for (var i in list) {
  29106. var item = list[i];
  29107. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29108. listByTags.push(item);
  29109. forEach(item);
  29110. }
  29111. }
  29112. return listByTags;
  29113. };
  29114. /**
  29115. * Get a list of meshes by tags
  29116. * @param tagsQuery defines the tags query to use
  29117. * @param forEach defines a predicate used to filter results
  29118. * @returns an array of Mesh
  29119. */
  29120. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29121. return this._getByTags(this.meshes, tagsQuery, forEach);
  29122. };
  29123. /**
  29124. * Get a list of cameras by tags
  29125. * @param tagsQuery defines the tags query to use
  29126. * @param forEach defines a predicate used to filter results
  29127. * @returns an array of Camera
  29128. */
  29129. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29130. return this._getByTags(this.cameras, tagsQuery, forEach);
  29131. };
  29132. /**
  29133. * Get a list of lights by tags
  29134. * @param tagsQuery defines the tags query to use
  29135. * @param forEach defines a predicate used to filter results
  29136. * @returns an array of Light
  29137. */
  29138. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29139. return this._getByTags(this.lights, tagsQuery, forEach);
  29140. };
  29141. /**
  29142. * Get a list of materials by tags
  29143. * @param tagsQuery defines the tags query to use
  29144. * @param forEach defines a predicate used to filter results
  29145. * @returns an array of Material
  29146. */
  29147. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29148. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29149. };
  29150. /**
  29151. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29152. * This allowed control for front to back rendering or reversly depending of the special needs.
  29153. *
  29154. * @param renderingGroupId The rendering group id corresponding to its index
  29155. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29156. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29157. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29158. */
  29159. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29160. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29161. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29162. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29163. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29164. };
  29165. /**
  29166. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29167. *
  29168. * @param renderingGroupId The rendering group id corresponding to its index
  29169. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29170. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29171. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29172. */
  29173. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29174. if (depth === void 0) { depth = true; }
  29175. if (stencil === void 0) { stencil = true; }
  29176. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29177. };
  29178. /**
  29179. * Will flag all materials as dirty to trigger new shader compilation
  29180. * @param flag defines the flag used to specify which material part must be marked as dirty
  29181. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29182. */
  29183. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29184. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29185. var material = _a[_i];
  29186. if (predicate && !predicate(material)) {
  29187. continue;
  29188. }
  29189. material.markAsDirty(flag);
  29190. }
  29191. };
  29192. /** @hidden */
  29193. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29194. var _this = this;
  29195. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29196. this._activeRequests.push(request);
  29197. request.onCompleteObservable.add(function (request) {
  29198. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29199. });
  29200. return request;
  29201. };
  29202. /** @hidden */
  29203. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29204. var _this = this;
  29205. return new Promise(function (resolve, reject) {
  29206. _this._loadFile(url, function (data) {
  29207. resolve(data);
  29208. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29209. reject(exception);
  29210. });
  29211. });
  29212. };
  29213. // Statics
  29214. Scene._FOGMODE_NONE = 0;
  29215. Scene._FOGMODE_EXP = 1;
  29216. Scene._FOGMODE_EXP2 = 2;
  29217. Scene._FOGMODE_LINEAR = 3;
  29218. Scene._uniqueIdCounter = 0;
  29219. /**
  29220. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29221. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29222. */
  29223. Scene.MinDeltaTime = 1.0;
  29224. /**
  29225. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29226. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29227. */
  29228. Scene.MaxDeltaTime = 1000.0;
  29229. /** The distance in pixel that you have to move to prevent some events */
  29230. Scene.DragMovementThreshold = 10; // in pixels
  29231. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29232. Scene.LongPressDelay = 500; // in milliseconds
  29233. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29234. Scene.DoubleClickDelay = 300; // in milliseconds
  29235. /** If you need to check double click without raising a single click at first click, enable this flag */
  29236. Scene.ExclusiveDoubleClickMode = false;
  29237. return Scene;
  29238. }());
  29239. BABYLON.Scene = Scene;
  29240. })(BABYLON || (BABYLON = {}));
  29241. //# sourceMappingURL=babylon.scene.js.map
  29242. var BABYLON;
  29243. (function (BABYLON) {
  29244. /**
  29245. * Set of assets to keep when moving a scene into an asset container.
  29246. */
  29247. var KeepAssets = /** @class */ (function () {
  29248. function KeepAssets() {
  29249. /**
  29250. * Cameras to keep.
  29251. */
  29252. this.cameras = new Array();
  29253. /**
  29254. * Lights to keep.
  29255. */
  29256. this.lights = new Array();
  29257. /**
  29258. * Meshes to keep.
  29259. */
  29260. this.meshes = new Array();
  29261. /**
  29262. * Skeletons to keep.
  29263. */
  29264. this.skeletons = new Array();
  29265. /**
  29266. * ParticleSystems to keep.
  29267. */
  29268. this.particleSystems = new Array();
  29269. /**
  29270. * Animations to keep.
  29271. */
  29272. this.animations = new Array();
  29273. /**
  29274. * AnimationGroups to keep.
  29275. */
  29276. this.animationGroups = new Array();
  29277. /**
  29278. * MultiMaterials to keep.
  29279. */
  29280. this.multiMaterials = new Array();
  29281. /**
  29282. * Materials to keep.
  29283. */
  29284. this.materials = new Array();
  29285. /**
  29286. * MorphTargetManagers to keep.
  29287. */
  29288. this.morphTargetManagers = new Array();
  29289. /**
  29290. * Geometries to keep.
  29291. */
  29292. this.geometries = new Array();
  29293. /**
  29294. * TransformNodes to keep.
  29295. */
  29296. this.transformNodes = new Array();
  29297. /**
  29298. * LensFlareSystems to keep.
  29299. */
  29300. this.lensFlareSystems = new Array();
  29301. /**
  29302. * ShadowGenerators to keep.
  29303. */
  29304. this.shadowGenerators = new Array();
  29305. /**
  29306. * ActionManagers to keep.
  29307. */
  29308. this.actionManagers = new Array();
  29309. /**
  29310. * Sounds to keep.
  29311. */
  29312. this.sounds = new Array();
  29313. /**
  29314. * Textures to keep.
  29315. */
  29316. this.textures = new Array();
  29317. /**
  29318. * Effect layers to keep.
  29319. */
  29320. this.effectLayers = new Array();
  29321. }
  29322. return KeepAssets;
  29323. }());
  29324. BABYLON.KeepAssets = KeepAssets;
  29325. /**
  29326. * Container with a set of assets that can be added or removed from a scene.
  29327. */
  29328. var AssetContainer = /** @class */ (function () {
  29329. /**
  29330. * Instantiates an AssetContainer.
  29331. * @param scene The scene the AssetContainer belongs to.
  29332. */
  29333. function AssetContainer(scene) {
  29334. // Objects
  29335. /**
  29336. * Cameras populated in the container.
  29337. */
  29338. this.cameras = new Array();
  29339. /**
  29340. * Lights populated in the container.
  29341. */
  29342. this.lights = new Array();
  29343. /**
  29344. * Meshes populated in the container.
  29345. */
  29346. this.meshes = new Array();
  29347. /**
  29348. * Skeletons populated in the container.
  29349. */
  29350. this.skeletons = new Array();
  29351. /**
  29352. * ParticleSystems populated in the container.
  29353. */
  29354. this.particleSystems = new Array();
  29355. /**
  29356. * Animations populated in the container.
  29357. */
  29358. this.animations = new Array();
  29359. /**
  29360. * AnimationGroups populated in the container.
  29361. */
  29362. this.animationGroups = new Array();
  29363. /**
  29364. * MultiMaterials populated in the container.
  29365. */
  29366. this.multiMaterials = new Array();
  29367. /**
  29368. * Materials populated in the container.
  29369. */
  29370. this.materials = new Array();
  29371. /**
  29372. * MorphTargetManagers populated in the container.
  29373. */
  29374. this.morphTargetManagers = new Array();
  29375. /**
  29376. * Geometries populated in the container.
  29377. */
  29378. this.geometries = new Array();
  29379. /**
  29380. * TransformNodes populated in the container.
  29381. */
  29382. this.transformNodes = new Array();
  29383. /**
  29384. * LensFlareSystems populated in the container.
  29385. */
  29386. this.lensFlareSystems = new Array();
  29387. /**
  29388. * ShadowGenerators populated in the container.
  29389. */
  29390. this.shadowGenerators = new Array();
  29391. /**
  29392. * ActionManagers populated in the container.
  29393. */
  29394. this.actionManagers = new Array();
  29395. /**
  29396. * Sounds populated in the container.
  29397. */
  29398. this.sounds = new Array();
  29399. /**
  29400. * Textures populated in the container.
  29401. */
  29402. this.textures = new Array();
  29403. /**
  29404. * Effect layers populated in the container.
  29405. */
  29406. this.effectLayers = new Array();
  29407. this.scene = scene;
  29408. }
  29409. /**
  29410. * Adds all the assets from the container to the scene.
  29411. */
  29412. AssetContainer.prototype.addAllToScene = function () {
  29413. var _this = this;
  29414. this.cameras.forEach(function (o) {
  29415. _this.scene.addCamera(o);
  29416. });
  29417. this.lights.forEach(function (o) {
  29418. _this.scene.addLight(o);
  29419. });
  29420. this.meshes.forEach(function (o) {
  29421. _this.scene.addMesh(o);
  29422. });
  29423. this.skeletons.forEach(function (o) {
  29424. _this.scene.addSkeleton(o);
  29425. });
  29426. this.particleSystems.forEach(function (o) {
  29427. _this.scene.addParticleSystem(o);
  29428. });
  29429. this.animations.forEach(function (o) {
  29430. _this.scene.addAnimation(o);
  29431. });
  29432. this.animationGroups.forEach(function (o) {
  29433. _this.scene.addAnimationGroup(o);
  29434. });
  29435. this.multiMaterials.forEach(function (o) {
  29436. _this.scene.addMultiMaterial(o);
  29437. });
  29438. this.materials.forEach(function (o) {
  29439. _this.scene.addMaterial(o);
  29440. });
  29441. this.morphTargetManagers.forEach(function (o) {
  29442. _this.scene.addMorphTargetManager(o);
  29443. });
  29444. this.geometries.forEach(function (o) {
  29445. _this.scene.addGeometry(o);
  29446. });
  29447. this.transformNodes.forEach(function (o) {
  29448. _this.scene.addTransformNode(o);
  29449. });
  29450. this.lensFlareSystems.forEach(function (o) {
  29451. _this.scene.addLensFlareSystem(o);
  29452. });
  29453. this.actionManagers.forEach(function (o) {
  29454. _this.scene.addActionManager(o);
  29455. });
  29456. this.sounds.forEach(function (o) {
  29457. o.play();
  29458. o.autoplay = true;
  29459. _this.scene.mainSoundTrack.AddSound(o);
  29460. });
  29461. this.textures.forEach(function (o) {
  29462. _this.scene.addTexture(o);
  29463. });
  29464. this.effectLayers.forEach(function (o) {
  29465. _this.scene.addEffectLayer(o);
  29466. });
  29467. };
  29468. /**
  29469. * Removes all the assets in the container from the scene
  29470. */
  29471. AssetContainer.prototype.removeAllFromScene = function () {
  29472. var _this = this;
  29473. this.cameras.forEach(function (o) {
  29474. _this.scene.removeCamera(o);
  29475. });
  29476. this.lights.forEach(function (o) {
  29477. _this.scene.removeLight(o);
  29478. });
  29479. this.meshes.forEach(function (o) {
  29480. _this.scene.removeMesh(o);
  29481. });
  29482. this.skeletons.forEach(function (o) {
  29483. _this.scene.removeSkeleton(o);
  29484. });
  29485. this.particleSystems.forEach(function (o) {
  29486. _this.scene.removeParticleSystem(o);
  29487. });
  29488. this.animations.forEach(function (o) {
  29489. _this.scene.removeAnimation(o);
  29490. });
  29491. this.animationGroups.forEach(function (o) {
  29492. _this.scene.removeAnimationGroup(o);
  29493. });
  29494. this.multiMaterials.forEach(function (o) {
  29495. _this.scene.removeMultiMaterial(o);
  29496. });
  29497. this.materials.forEach(function (o) {
  29498. _this.scene.removeMaterial(o);
  29499. });
  29500. this.morphTargetManagers.forEach(function (o) {
  29501. _this.scene.removeMorphTargetManager(o);
  29502. });
  29503. this.geometries.forEach(function (o) {
  29504. _this.scene.removeGeometry(o);
  29505. });
  29506. this.transformNodes.forEach(function (o) {
  29507. _this.scene.removeTransformNode(o);
  29508. });
  29509. this.lensFlareSystems.forEach(function (o) {
  29510. _this.scene.removeLensFlareSystem(o);
  29511. });
  29512. this.actionManagers.forEach(function (o) {
  29513. _this.scene.removeActionManager(o);
  29514. });
  29515. this.sounds.forEach(function (o) {
  29516. o.stop();
  29517. o.autoplay = false;
  29518. _this.scene.mainSoundTrack.RemoveSound(o);
  29519. });
  29520. this.textures.forEach(function (o) {
  29521. _this.scene.removeTexture(o);
  29522. });
  29523. this.effectLayers.forEach(function (o) {
  29524. _this.scene.removeEffectLayer(o);
  29525. });
  29526. };
  29527. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29528. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29529. var asset = sourceAssets_1[_i];
  29530. var move = true;
  29531. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29532. var keepAsset = keepAssets_1[_a];
  29533. if (asset === keepAsset) {
  29534. move = false;
  29535. break;
  29536. }
  29537. }
  29538. if (move) {
  29539. targetAssets.push(asset);
  29540. }
  29541. }
  29542. };
  29543. /**
  29544. * Removes all the assets contained in the scene and adds them to the container.
  29545. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29546. */
  29547. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29548. if (keepAssets === undefined) {
  29549. keepAssets = new KeepAssets();
  29550. }
  29551. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29552. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29553. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29554. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29555. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29556. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29557. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29558. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29559. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29560. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29561. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29562. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29563. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29564. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29565. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29566. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29567. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29568. this.removeAllFromScene();
  29569. };
  29570. /**
  29571. * 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.
  29572. * @returns the root mesh
  29573. */
  29574. AssetContainer.prototype.createRootMesh = function () {
  29575. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29576. this.meshes.forEach(function (m) {
  29577. if (!m.parent) {
  29578. rootMesh.addChild(m);
  29579. }
  29580. });
  29581. this.meshes.unshift(rootMesh);
  29582. return rootMesh;
  29583. };
  29584. return AssetContainer;
  29585. }());
  29586. BABYLON.AssetContainer = AssetContainer;
  29587. })(BABYLON || (BABYLON = {}));
  29588. //# sourceMappingURL=babylon.assetContainer.js.map
  29589. var BABYLON;
  29590. (function (BABYLON) {
  29591. var Buffer = /** @class */ (function () {
  29592. /**
  29593. * Constructor
  29594. * @param engine the engine
  29595. * @param data the data to use for this buffer
  29596. * @param updatable whether the data is updatable
  29597. * @param stride the stride (optional)
  29598. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29599. * @param instanced whether the buffer is instanced (optional)
  29600. * @param useBytes set to true if the stride in in bytes (optional)
  29601. */
  29602. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29603. if (stride === void 0) { stride = 0; }
  29604. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29605. if (instanced === void 0) { instanced = false; }
  29606. if (useBytes === void 0) { useBytes = false; }
  29607. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29608. this._engine = engine.getScene().getEngine();
  29609. }
  29610. else {
  29611. this._engine = engine;
  29612. }
  29613. this._updatable = updatable;
  29614. this._instanced = instanced;
  29615. this._data = data;
  29616. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29617. if (!postponeInternalCreation) { // by default
  29618. this.create();
  29619. }
  29620. }
  29621. /**
  29622. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29623. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29624. * @param offset defines offset in the buffer (0 by default)
  29625. * @param size defines the size in floats of attributes (position is 3 for instance)
  29626. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29627. * @param instanced defines if the vertex buffer contains indexed data
  29628. * @param useBytes defines if the offset and stride are in bytes
  29629. * @returns the new vertex buffer
  29630. */
  29631. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29632. if (useBytes === void 0) { useBytes = false; }
  29633. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29634. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29635. // a lot of these parameters are ignored as they are overriden by the buffer
  29636. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29637. };
  29638. // Properties
  29639. Buffer.prototype.isUpdatable = function () {
  29640. return this._updatable;
  29641. };
  29642. Buffer.prototype.getData = function () {
  29643. return this._data;
  29644. };
  29645. Buffer.prototype.getBuffer = function () {
  29646. return this._buffer;
  29647. };
  29648. /**
  29649. * Gets the stride in float32 units (i.e. byte stride / 4).
  29650. * May not be an integer if the byte stride is not divisible by 4.
  29651. * DEPRECATED. Use byteStride instead.
  29652. * @returns the stride in float32 units
  29653. */
  29654. Buffer.prototype.getStrideSize = function () {
  29655. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29656. };
  29657. // Methods
  29658. Buffer.prototype.create = function (data) {
  29659. if (data === void 0) { data = null; }
  29660. if (!data && this._buffer) {
  29661. return; // nothing to do
  29662. }
  29663. data = data || this._data;
  29664. if (!data) {
  29665. return;
  29666. }
  29667. if (!this._buffer) { // create buffer
  29668. if (this._updatable) {
  29669. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29670. this._data = data;
  29671. }
  29672. else {
  29673. this._buffer = this._engine.createVertexBuffer(data);
  29674. }
  29675. }
  29676. else if (this._updatable) { // update buffer
  29677. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29678. this._data = data;
  29679. }
  29680. };
  29681. Buffer.prototype._rebuild = function () {
  29682. this._buffer = null;
  29683. this.create(this._data);
  29684. };
  29685. Buffer.prototype.update = function (data) {
  29686. this.create(data);
  29687. };
  29688. /**
  29689. * Updates the data directly.
  29690. * @param data the new data
  29691. * @param offset the new offset
  29692. * @param vertexCount the vertex count (optional)
  29693. * @param useBytes set to true if the offset is in bytes
  29694. */
  29695. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29696. if (useBytes === void 0) { useBytes = false; }
  29697. if (!this._buffer) {
  29698. return;
  29699. }
  29700. if (this._updatable) { // update buffer
  29701. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29702. this._data = null;
  29703. }
  29704. };
  29705. Buffer.prototype.dispose = function () {
  29706. if (!this._buffer) {
  29707. return;
  29708. }
  29709. if (this._engine._releaseBuffer(this._buffer)) {
  29710. this._buffer = null;
  29711. }
  29712. };
  29713. return Buffer;
  29714. }());
  29715. BABYLON.Buffer = Buffer;
  29716. })(BABYLON || (BABYLON = {}));
  29717. //# sourceMappingURL=babylon.buffer.js.map
  29718. var BABYLON;
  29719. (function (BABYLON) {
  29720. var VertexBuffer = /** @class */ (function () {
  29721. /**
  29722. * Constructor
  29723. * @param engine the engine
  29724. * @param data the data to use for this vertex buffer
  29725. * @param kind the vertex buffer kind
  29726. * @param updatable whether the data is updatable
  29727. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29728. * @param stride the stride (optional)
  29729. * @param instanced whether the buffer is instanced (optional)
  29730. * @param offset the offset of the data (optional)
  29731. * @param size the number of components (optional)
  29732. * @param type the type of the component (optional)
  29733. * @param normalized whether the data contains normalized data (optional)
  29734. * @param useBytes set to true if stride and offset are in bytes (optional)
  29735. */
  29736. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29737. if (normalized === void 0) { normalized = false; }
  29738. if (useBytes === void 0) { useBytes = false; }
  29739. if (data instanceof BABYLON.Buffer) {
  29740. this._buffer = data;
  29741. this._ownsBuffer = false;
  29742. }
  29743. else {
  29744. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29745. this._ownsBuffer = true;
  29746. }
  29747. this._kind = kind;
  29748. if (type == undefined) {
  29749. var data_1 = this.getData();
  29750. this.type = VertexBuffer.FLOAT;
  29751. if (data_1 instanceof Int8Array)
  29752. this.type = VertexBuffer.BYTE;
  29753. else if (data_1 instanceof Uint8Array)
  29754. this.type = VertexBuffer.UNSIGNED_BYTE;
  29755. else if (data_1 instanceof Int16Array)
  29756. this.type = VertexBuffer.SHORT;
  29757. else if (data_1 instanceof Uint16Array)
  29758. this.type = VertexBuffer.UNSIGNED_SHORT;
  29759. else if (data_1 instanceof Int32Array)
  29760. this.type = VertexBuffer.INT;
  29761. else if (data_1 instanceof Uint32Array)
  29762. this.type = VertexBuffer.UNSIGNED_INT;
  29763. }
  29764. else {
  29765. this.type = type;
  29766. }
  29767. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29768. if (useBytes) {
  29769. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29770. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29771. this.byteOffset = offset || 0;
  29772. }
  29773. else {
  29774. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29775. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29776. this.byteOffset = (offset || 0) * typeByteLength;
  29777. }
  29778. this.normalized = normalized;
  29779. this._instanced = instanced !== undefined ? instanced : false;
  29780. this._instanceDivisor = instanced ? 1 : 0;
  29781. }
  29782. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29783. /**
  29784. * Gets or sets the instance divisor when in instanced mode
  29785. */
  29786. get: function () {
  29787. return this._instanceDivisor;
  29788. },
  29789. set: function (value) {
  29790. this._instanceDivisor = value;
  29791. if (value == 0) {
  29792. this._instanced = false;
  29793. }
  29794. else {
  29795. this._instanced = true;
  29796. }
  29797. },
  29798. enumerable: true,
  29799. configurable: true
  29800. });
  29801. VertexBuffer.prototype._rebuild = function () {
  29802. if (!this._buffer) {
  29803. return;
  29804. }
  29805. this._buffer._rebuild();
  29806. };
  29807. /**
  29808. * Returns the kind of the VertexBuffer (string).
  29809. */
  29810. VertexBuffer.prototype.getKind = function () {
  29811. return this._kind;
  29812. };
  29813. // Properties
  29814. /**
  29815. * Boolean : is the VertexBuffer updatable ?
  29816. */
  29817. VertexBuffer.prototype.isUpdatable = function () {
  29818. return this._buffer.isUpdatable();
  29819. };
  29820. /**
  29821. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29822. */
  29823. VertexBuffer.prototype.getData = function () {
  29824. return this._buffer.getData();
  29825. };
  29826. /**
  29827. * Returns the WebGLBuffer associated to the VertexBuffer.
  29828. */
  29829. VertexBuffer.prototype.getBuffer = function () {
  29830. return this._buffer.getBuffer();
  29831. };
  29832. /**
  29833. * Returns the stride as a multiple of the type byte length.
  29834. * DEPRECATED. Use byteStride instead.
  29835. */
  29836. VertexBuffer.prototype.getStrideSize = function () {
  29837. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29838. };
  29839. /**
  29840. * Returns the offset as a multiple of the type byte length.
  29841. * DEPRECATED. Use byteOffset instead.
  29842. */
  29843. VertexBuffer.prototype.getOffset = function () {
  29844. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29845. };
  29846. /**
  29847. * Returns the number of components per vertex attribute (integer).
  29848. */
  29849. VertexBuffer.prototype.getSize = function () {
  29850. return this._size;
  29851. };
  29852. /**
  29853. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29854. */
  29855. VertexBuffer.prototype.getIsInstanced = function () {
  29856. return this._instanced;
  29857. };
  29858. /**
  29859. * Returns the instancing divisor, zero for non-instanced (integer).
  29860. */
  29861. VertexBuffer.prototype.getInstanceDivisor = function () {
  29862. return this._instanceDivisor;
  29863. };
  29864. // Methods
  29865. /**
  29866. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29867. * Returns the created WebGLBuffer.
  29868. */
  29869. VertexBuffer.prototype.create = function (data) {
  29870. return this._buffer.create(data);
  29871. };
  29872. /**
  29873. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29874. * This function will create a new buffer if the current one is not updatable
  29875. * Returns the updated WebGLBuffer.
  29876. */
  29877. VertexBuffer.prototype.update = function (data) {
  29878. return this._buffer.update(data);
  29879. };
  29880. /**
  29881. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29882. * Returns the directly updated WebGLBuffer.
  29883. * @param data the new data
  29884. * @param offset the new offset
  29885. * @param useBytes set to true if the offset is in bytes
  29886. */
  29887. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29888. if (useBytes === void 0) { useBytes = false; }
  29889. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29890. };
  29891. /**
  29892. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29893. */
  29894. VertexBuffer.prototype.dispose = function () {
  29895. if (this._ownsBuffer) {
  29896. this._buffer.dispose();
  29897. }
  29898. };
  29899. /**
  29900. * Enumerates each value of this vertex buffer as numbers.
  29901. * @param count the number of values to enumerate
  29902. * @param callback the callback function called for each value
  29903. */
  29904. VertexBuffer.prototype.forEach = function (count, callback) {
  29905. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29906. };
  29907. Object.defineProperty(VertexBuffer, "PositionKind", {
  29908. get: function () {
  29909. return VertexBuffer._PositionKind;
  29910. },
  29911. enumerable: true,
  29912. configurable: true
  29913. });
  29914. Object.defineProperty(VertexBuffer, "NormalKind", {
  29915. get: function () {
  29916. return VertexBuffer._NormalKind;
  29917. },
  29918. enumerable: true,
  29919. configurable: true
  29920. });
  29921. Object.defineProperty(VertexBuffer, "TangentKind", {
  29922. get: function () {
  29923. return VertexBuffer._TangentKind;
  29924. },
  29925. enumerable: true,
  29926. configurable: true
  29927. });
  29928. Object.defineProperty(VertexBuffer, "UVKind", {
  29929. get: function () {
  29930. return VertexBuffer._UVKind;
  29931. },
  29932. enumerable: true,
  29933. configurable: true
  29934. });
  29935. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29936. get: function () {
  29937. return VertexBuffer._UV2Kind;
  29938. },
  29939. enumerable: true,
  29940. configurable: true
  29941. });
  29942. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29943. get: function () {
  29944. return VertexBuffer._UV3Kind;
  29945. },
  29946. enumerable: true,
  29947. configurable: true
  29948. });
  29949. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29950. get: function () {
  29951. return VertexBuffer._UV4Kind;
  29952. },
  29953. enumerable: true,
  29954. configurable: true
  29955. });
  29956. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29957. get: function () {
  29958. return VertexBuffer._UV5Kind;
  29959. },
  29960. enumerable: true,
  29961. configurable: true
  29962. });
  29963. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29964. get: function () {
  29965. return VertexBuffer._UV6Kind;
  29966. },
  29967. enumerable: true,
  29968. configurable: true
  29969. });
  29970. Object.defineProperty(VertexBuffer, "ColorKind", {
  29971. get: function () {
  29972. return VertexBuffer._ColorKind;
  29973. },
  29974. enumerable: true,
  29975. configurable: true
  29976. });
  29977. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29978. get: function () {
  29979. return VertexBuffer._MatricesIndicesKind;
  29980. },
  29981. enumerable: true,
  29982. configurable: true
  29983. });
  29984. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29985. get: function () {
  29986. return VertexBuffer._MatricesWeightsKind;
  29987. },
  29988. enumerable: true,
  29989. configurable: true
  29990. });
  29991. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29992. get: function () {
  29993. return VertexBuffer._MatricesIndicesExtraKind;
  29994. },
  29995. enumerable: true,
  29996. configurable: true
  29997. });
  29998. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29999. get: function () {
  30000. return VertexBuffer._MatricesWeightsExtraKind;
  30001. },
  30002. enumerable: true,
  30003. configurable: true
  30004. });
  30005. /**
  30006. * Deduces the stride given a kind.
  30007. * @param kind The kind string to deduce
  30008. * @returns The deduced stride
  30009. */
  30010. VertexBuffer.DeduceStride = function (kind) {
  30011. switch (kind) {
  30012. case VertexBuffer.UVKind:
  30013. case VertexBuffer.UV2Kind:
  30014. case VertexBuffer.UV3Kind:
  30015. case VertexBuffer.UV4Kind:
  30016. case VertexBuffer.UV5Kind:
  30017. case VertexBuffer.UV6Kind:
  30018. return 2;
  30019. case VertexBuffer.NormalKind:
  30020. case VertexBuffer.PositionKind:
  30021. return 3;
  30022. case VertexBuffer.ColorKind:
  30023. case VertexBuffer.MatricesIndicesKind:
  30024. case VertexBuffer.MatricesIndicesExtraKind:
  30025. case VertexBuffer.MatricesWeightsKind:
  30026. case VertexBuffer.MatricesWeightsExtraKind:
  30027. case VertexBuffer.TangentKind:
  30028. return 4;
  30029. default:
  30030. throw new Error("Invalid kind '" + kind + "'");
  30031. }
  30032. };
  30033. /**
  30034. * Gets the byte length of the given type.
  30035. * @param type the type
  30036. * @returns the number of bytes
  30037. */
  30038. VertexBuffer.GetTypeByteLength = function (type) {
  30039. switch (type) {
  30040. case VertexBuffer.BYTE:
  30041. case VertexBuffer.UNSIGNED_BYTE:
  30042. return 1;
  30043. case VertexBuffer.SHORT:
  30044. case VertexBuffer.UNSIGNED_SHORT:
  30045. return 2;
  30046. case VertexBuffer.INT:
  30047. case VertexBuffer.FLOAT:
  30048. return 4;
  30049. default:
  30050. throw new Error("Invalid type '" + type + "'");
  30051. }
  30052. };
  30053. /**
  30054. * Enumerates each value of the given parameters as numbers.
  30055. * @param data the data to enumerate
  30056. * @param byteOffset the byte offset of the data
  30057. * @param byteStride the byte stride of the data
  30058. * @param componentCount the number of components per element
  30059. * @param componentType the type of the component
  30060. * @param count the total number of components
  30061. * @param normalized whether the data is normalized
  30062. * @param callback the callback function called for each value
  30063. */
  30064. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30065. if (data instanceof Array) {
  30066. var offset = byteOffset / 4;
  30067. var stride = byteStride / 4;
  30068. for (var index = 0; index < count; index += componentCount) {
  30069. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30070. callback(data[offset + componentIndex], index + componentIndex);
  30071. }
  30072. offset += stride;
  30073. }
  30074. }
  30075. else {
  30076. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30077. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30078. for (var index = 0; index < count; index += componentCount) {
  30079. var componentByteOffset = byteOffset;
  30080. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30081. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30082. callback(value, index + componentIndex);
  30083. componentByteOffset += componentByteLength;
  30084. }
  30085. byteOffset += byteStride;
  30086. }
  30087. }
  30088. };
  30089. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30090. switch (type) {
  30091. case VertexBuffer.BYTE: {
  30092. var value = dataView.getInt8(byteOffset);
  30093. if (normalized) {
  30094. value = Math.max(value / 127, -1);
  30095. }
  30096. return value;
  30097. }
  30098. case VertexBuffer.UNSIGNED_BYTE: {
  30099. var value = dataView.getUint8(byteOffset);
  30100. if (normalized) {
  30101. value = value / 255;
  30102. }
  30103. return value;
  30104. }
  30105. case VertexBuffer.SHORT: {
  30106. var value = dataView.getInt16(byteOffset, true);
  30107. if (normalized) {
  30108. value = Math.max(value / 16383, -1);
  30109. }
  30110. return value;
  30111. }
  30112. case VertexBuffer.UNSIGNED_SHORT: {
  30113. var value = dataView.getUint16(byteOffset, true);
  30114. if (normalized) {
  30115. value = value / 65535;
  30116. }
  30117. return value;
  30118. }
  30119. case VertexBuffer.FLOAT: {
  30120. return dataView.getFloat32(byteOffset, true);
  30121. }
  30122. default: {
  30123. throw new Error("Invalid component type " + type);
  30124. }
  30125. }
  30126. };
  30127. /**
  30128. * The byte type.
  30129. */
  30130. VertexBuffer.BYTE = 5120;
  30131. /**
  30132. * The unsigned byte type.
  30133. */
  30134. VertexBuffer.UNSIGNED_BYTE = 5121;
  30135. /**
  30136. * The short type.
  30137. */
  30138. VertexBuffer.SHORT = 5122;
  30139. /**
  30140. * The unsigned short type.
  30141. */
  30142. VertexBuffer.UNSIGNED_SHORT = 5123;
  30143. /**
  30144. * The integer type.
  30145. */
  30146. VertexBuffer.INT = 5124;
  30147. /**
  30148. * The unsigned integer type.
  30149. */
  30150. VertexBuffer.UNSIGNED_INT = 5125;
  30151. /**
  30152. * The float type.
  30153. */
  30154. VertexBuffer.FLOAT = 5126;
  30155. // Enums
  30156. VertexBuffer._PositionKind = "position";
  30157. VertexBuffer._NormalKind = "normal";
  30158. VertexBuffer._TangentKind = "tangent";
  30159. VertexBuffer._UVKind = "uv";
  30160. VertexBuffer._UV2Kind = "uv2";
  30161. VertexBuffer._UV3Kind = "uv3";
  30162. VertexBuffer._UV4Kind = "uv4";
  30163. VertexBuffer._UV5Kind = "uv5";
  30164. VertexBuffer._UV6Kind = "uv6";
  30165. VertexBuffer._ColorKind = "color";
  30166. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30167. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30168. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30169. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30170. return VertexBuffer;
  30171. }());
  30172. BABYLON.VertexBuffer = VertexBuffer;
  30173. })(BABYLON || (BABYLON = {}));
  30174. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30175. var BABYLON;
  30176. (function (BABYLON) {
  30177. /**
  30178. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30179. */
  30180. var DummyInternalTextureTracker = /** @class */ (function () {
  30181. function DummyInternalTextureTracker() {
  30182. /**
  30183. * Gets or set the previous tracker in the list
  30184. */
  30185. this.previous = null;
  30186. /**
  30187. * Gets or set the next tracker in the list
  30188. */
  30189. this.next = null;
  30190. }
  30191. return DummyInternalTextureTracker;
  30192. }());
  30193. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30194. })(BABYLON || (BABYLON = {}));
  30195. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30196. var BABYLON;
  30197. (function (BABYLON) {
  30198. /**
  30199. * Class used to store data associated with WebGL texture data for the engine
  30200. * This class should not be used directly
  30201. */
  30202. var InternalTexture = /** @class */ (function () {
  30203. /**
  30204. * Creates a new InternalTexture
  30205. * @param engine defines the engine to use
  30206. * @param dataSource defines the type of data that will be used
  30207. */
  30208. function InternalTexture(engine, dataSource) {
  30209. /**
  30210. * Observable called when the texture is loaded
  30211. */
  30212. this.onLoadedObservable = new BABYLON.Observable();
  30213. /**
  30214. * Gets or set the previous tracker in the list
  30215. */
  30216. this.previous = null;
  30217. /**
  30218. * Gets or set the next tracker in the list
  30219. */
  30220. this.next = null;
  30221. // Private
  30222. /** @hidden */
  30223. this._initialSlot = -1;
  30224. /** @hidden */
  30225. this._designatedSlot = -1;
  30226. /** @hidden */
  30227. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30228. /** @hidden */
  30229. this._comparisonFunction = 0;
  30230. /** @hidden */
  30231. this._lodGenerationScale = 0;
  30232. /** @hidden */
  30233. this._lodGenerationOffset = 0;
  30234. /** @hidden */
  30235. this._isRGBD = false;
  30236. /** @hidden */
  30237. this._references = 1;
  30238. this._engine = engine;
  30239. this._dataSource = dataSource;
  30240. this._webGLTexture = engine._createTexture();
  30241. }
  30242. /**
  30243. * Gets the Engine the texture belongs to.
  30244. * @returns The babylon engine
  30245. */
  30246. InternalTexture.prototype.getEngine = function () {
  30247. return this._engine;
  30248. };
  30249. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30250. /**
  30251. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30252. */
  30253. get: function () {
  30254. return this._dataSource;
  30255. },
  30256. enumerable: true,
  30257. configurable: true
  30258. });
  30259. /**
  30260. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30261. */
  30262. InternalTexture.prototype.incrementReferences = function () {
  30263. this._references++;
  30264. };
  30265. /**
  30266. * Change the size of the texture (not the size of the content)
  30267. * @param width defines the new width
  30268. * @param height defines the new height
  30269. * @param depth defines the new depth (1 by default)
  30270. */
  30271. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30272. if (depth === void 0) { depth = 1; }
  30273. this.width = width;
  30274. this.height = height;
  30275. this.depth = depth;
  30276. this.baseWidth = width;
  30277. this.baseHeight = height;
  30278. this.baseDepth = depth;
  30279. this._size = width * height * depth;
  30280. };
  30281. /** @hidden */
  30282. InternalTexture.prototype._rebuild = function () {
  30283. var _this = this;
  30284. var proxy;
  30285. this.isReady = false;
  30286. this._cachedCoordinatesMode = null;
  30287. this._cachedWrapU = null;
  30288. this._cachedWrapV = null;
  30289. this._cachedAnisotropicFilteringLevel = null;
  30290. switch (this._dataSource) {
  30291. case InternalTexture.DATASOURCE_TEMP:
  30292. return;
  30293. case InternalTexture.DATASOURCE_URL:
  30294. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30295. _this.isReady = true;
  30296. }, null, this._buffer, undefined, this.format);
  30297. proxy._swapAndDie(this);
  30298. return;
  30299. case InternalTexture.DATASOURCE_RAW:
  30300. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30301. proxy._swapAndDie(this);
  30302. this.isReady = true;
  30303. return;
  30304. case InternalTexture.DATASOURCE_RAW3D:
  30305. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30306. proxy._swapAndDie(this);
  30307. this.isReady = true;
  30308. return;
  30309. case InternalTexture.DATASOURCE_DYNAMIC:
  30310. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30311. proxy._swapAndDie(this);
  30312. // The engine will make sure to update content so no need to flag it as isReady = true
  30313. return;
  30314. case InternalTexture.DATASOURCE_RENDERTARGET:
  30315. var options = new BABYLON.RenderTargetCreationOptions();
  30316. options.generateDepthBuffer = this._generateDepthBuffer;
  30317. options.generateMipMaps = this.generateMipMaps;
  30318. options.generateStencilBuffer = this._generateStencilBuffer;
  30319. options.samplingMode = this.samplingMode;
  30320. options.type = this.type;
  30321. if (this.isCube) {
  30322. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30323. }
  30324. else {
  30325. var size = {
  30326. width: this.width,
  30327. height: this.height
  30328. };
  30329. proxy = this._engine.createRenderTargetTexture(size, options);
  30330. }
  30331. proxy._swapAndDie(this);
  30332. this.isReady = true;
  30333. return;
  30334. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30335. var depthTextureOptions = {
  30336. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30337. comparisonFunction: this._comparisonFunction,
  30338. generateStencil: this._generateStencilBuffer,
  30339. isCube: this.isCube
  30340. };
  30341. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30342. proxy._swapAndDie(this);
  30343. this.isReady = true;
  30344. return;
  30345. case InternalTexture.DATASOURCE_CUBE:
  30346. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30347. _this.isReady = true;
  30348. }, null, this.format, this._extension);
  30349. proxy._swapAndDie(this);
  30350. return;
  30351. case InternalTexture.DATASOURCE_CUBERAW:
  30352. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30353. proxy._swapAndDie(this);
  30354. this.isReady = true;
  30355. return;
  30356. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30357. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30358. if (proxy) {
  30359. proxy._swapAndDie(_this);
  30360. }
  30361. _this.isReady = true;
  30362. }, null, this.format, this._extension);
  30363. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30364. return;
  30365. }
  30366. };
  30367. InternalTexture.prototype._swapAndDie = function (target) {
  30368. target._webGLTexture = this._webGLTexture;
  30369. if (this._framebuffer) {
  30370. target._framebuffer = this._framebuffer;
  30371. }
  30372. if (this._depthStencilBuffer) {
  30373. target._depthStencilBuffer = this._depthStencilBuffer;
  30374. }
  30375. if (this._lodTextureHigh) {
  30376. if (target._lodTextureHigh) {
  30377. target._lodTextureHigh.dispose();
  30378. }
  30379. target._lodTextureHigh = this._lodTextureHigh;
  30380. }
  30381. if (this._lodTextureMid) {
  30382. if (target._lodTextureMid) {
  30383. target._lodTextureMid.dispose();
  30384. }
  30385. target._lodTextureMid = this._lodTextureMid;
  30386. }
  30387. if (this._lodTextureLow) {
  30388. if (target._lodTextureLow) {
  30389. target._lodTextureLow.dispose();
  30390. }
  30391. target._lodTextureLow = this._lodTextureLow;
  30392. }
  30393. var cache = this._engine.getLoadedTexturesCache();
  30394. var index = cache.indexOf(this);
  30395. if (index !== -1) {
  30396. cache.splice(index, 1);
  30397. }
  30398. };
  30399. /**
  30400. * Dispose the current allocated resources
  30401. */
  30402. InternalTexture.prototype.dispose = function () {
  30403. if (!this._webGLTexture) {
  30404. return;
  30405. }
  30406. this._references--;
  30407. if (this._references === 0) {
  30408. this._engine._releaseTexture(this);
  30409. this._webGLTexture = null;
  30410. this.previous = null;
  30411. this.next = null;
  30412. }
  30413. };
  30414. /**
  30415. * The source of the texture data is unknown
  30416. */
  30417. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30418. /**
  30419. * Texture data comes from an URL
  30420. */
  30421. InternalTexture.DATASOURCE_URL = 1;
  30422. /**
  30423. * Texture data is only used for temporary storage
  30424. */
  30425. InternalTexture.DATASOURCE_TEMP = 2;
  30426. /**
  30427. * Texture data comes from raw data (ArrayBuffer)
  30428. */
  30429. InternalTexture.DATASOURCE_RAW = 3;
  30430. /**
  30431. * Texture content is dynamic (video or dynamic texture)
  30432. */
  30433. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30434. /**
  30435. * Texture content is generated by rendering to it
  30436. */
  30437. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30438. /**
  30439. * Texture content is part of a multi render target process
  30440. */
  30441. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30442. /**
  30443. * Texture data comes from a cube data file
  30444. */
  30445. InternalTexture.DATASOURCE_CUBE = 7;
  30446. /**
  30447. * Texture data comes from a raw cube data
  30448. */
  30449. InternalTexture.DATASOURCE_CUBERAW = 8;
  30450. /**
  30451. * Texture data come from a prefiltered cube data file
  30452. */
  30453. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30454. /**
  30455. * Texture content is raw 3D data
  30456. */
  30457. InternalTexture.DATASOURCE_RAW3D = 10;
  30458. /**
  30459. * Texture content is a depth texture
  30460. */
  30461. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30462. return InternalTexture;
  30463. }());
  30464. BABYLON.InternalTexture = InternalTexture;
  30465. })(BABYLON || (BABYLON = {}));
  30466. //# sourceMappingURL=babylon.internalTexture.js.map
  30467. var BABYLON;
  30468. (function (BABYLON) {
  30469. var BaseTexture = /** @class */ (function () {
  30470. function BaseTexture(scene) {
  30471. this._hasAlpha = false;
  30472. this.getAlphaFromRGB = false;
  30473. this.level = 1;
  30474. this.coordinatesIndex = 0;
  30475. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30476. /**
  30477. * | Value | Type | Description |
  30478. * | ----- | ------------------ | ----------- |
  30479. * | 0 | CLAMP_ADDRESSMODE | |
  30480. * | 1 | WRAP_ADDRESSMODE | |
  30481. * | 2 | MIRROR_ADDRESSMODE | |
  30482. */
  30483. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30484. /**
  30485. * | Value | Type | Description |
  30486. * | ----- | ------------------ | ----------- |
  30487. * | 0 | CLAMP_ADDRESSMODE | |
  30488. * | 1 | WRAP_ADDRESSMODE | |
  30489. * | 2 | MIRROR_ADDRESSMODE | |
  30490. */
  30491. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30492. /**
  30493. * | Value | Type | Description |
  30494. * | ----- | ------------------ | ----------- |
  30495. * | 0 | CLAMP_ADDRESSMODE | |
  30496. * | 1 | WRAP_ADDRESSMODE | |
  30497. * | 2 | MIRROR_ADDRESSMODE | |
  30498. */
  30499. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30500. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30501. this.isCube = false;
  30502. this.is3D = false;
  30503. this.gammaSpace = true;
  30504. this.invertZ = false;
  30505. this.lodLevelInAlpha = false;
  30506. this.isRenderTarget = false;
  30507. this.animations = new Array();
  30508. /**
  30509. * An event triggered when the texture is disposed.
  30510. */
  30511. this.onDisposeObservable = new BABYLON.Observable();
  30512. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30513. this._cachedSize = BABYLON.Size.Zero();
  30514. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30515. if (this._scene) {
  30516. this._scene.textures.push(this);
  30517. }
  30518. this._uid = null;
  30519. }
  30520. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30521. get: function () {
  30522. return this._hasAlpha;
  30523. },
  30524. set: function (value) {
  30525. if (this._hasAlpha === value) {
  30526. return;
  30527. }
  30528. this._hasAlpha = value;
  30529. if (this._scene) {
  30530. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30531. }
  30532. },
  30533. enumerable: true,
  30534. configurable: true
  30535. });
  30536. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30537. get: function () {
  30538. return this._coordinatesMode;
  30539. },
  30540. /**
  30541. * How a texture is mapped.
  30542. *
  30543. * | Value | Type | Description |
  30544. * | ----- | ----------------------------------- | ----------- |
  30545. * | 0 | EXPLICIT_MODE | |
  30546. * | 1 | SPHERICAL_MODE | |
  30547. * | 2 | PLANAR_MODE | |
  30548. * | 3 | CUBIC_MODE | |
  30549. * | 4 | PROJECTION_MODE | |
  30550. * | 5 | SKYBOX_MODE | |
  30551. * | 6 | INVCUBIC_MODE | |
  30552. * | 7 | EQUIRECTANGULAR_MODE | |
  30553. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30554. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30555. */
  30556. set: function (value) {
  30557. if (this._coordinatesMode === value) {
  30558. return;
  30559. }
  30560. this._coordinatesMode = value;
  30561. if (this._scene) {
  30562. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30563. }
  30564. },
  30565. enumerable: true,
  30566. configurable: true
  30567. });
  30568. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30569. /**
  30570. * Gets whether or not the texture contains RGBD data.
  30571. */
  30572. get: function () {
  30573. return this._texture != null && this._texture._isRGBD;
  30574. },
  30575. enumerable: true,
  30576. configurable: true
  30577. });
  30578. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30579. get: function () {
  30580. if (this._texture)
  30581. return this._texture._lodGenerationOffset;
  30582. return 0.0;
  30583. },
  30584. set: function (value) {
  30585. if (this._texture)
  30586. this._texture._lodGenerationOffset = value;
  30587. },
  30588. enumerable: true,
  30589. configurable: true
  30590. });
  30591. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30592. get: function () {
  30593. if (this._texture)
  30594. return this._texture._lodGenerationScale;
  30595. return 0.0;
  30596. },
  30597. set: function (value) {
  30598. if (this._texture)
  30599. this._texture._lodGenerationScale = value;
  30600. },
  30601. enumerable: true,
  30602. configurable: true
  30603. });
  30604. Object.defineProperty(BaseTexture.prototype, "uid", {
  30605. get: function () {
  30606. if (!this._uid) {
  30607. this._uid = BABYLON.Tools.RandomId();
  30608. }
  30609. return this._uid;
  30610. },
  30611. enumerable: true,
  30612. configurable: true
  30613. });
  30614. BaseTexture.prototype.toString = function () {
  30615. return this.name;
  30616. };
  30617. BaseTexture.prototype.getClassName = function () {
  30618. return "BaseTexture";
  30619. };
  30620. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30621. set: function (callback) {
  30622. if (this._onDisposeObserver) {
  30623. this.onDisposeObservable.remove(this._onDisposeObserver);
  30624. }
  30625. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30626. },
  30627. enumerable: true,
  30628. configurable: true
  30629. });
  30630. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30631. get: function () {
  30632. return true;
  30633. },
  30634. enumerable: true,
  30635. configurable: true
  30636. });
  30637. BaseTexture.prototype.getScene = function () {
  30638. return this._scene;
  30639. };
  30640. BaseTexture.prototype.getTextureMatrix = function () {
  30641. return BABYLON.Matrix.IdentityReadOnly;
  30642. };
  30643. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30644. return BABYLON.Matrix.IdentityReadOnly;
  30645. };
  30646. BaseTexture.prototype.getInternalTexture = function () {
  30647. return this._texture;
  30648. };
  30649. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30650. return !this.isBlocking || this.isReady();
  30651. };
  30652. BaseTexture.prototype.isReady = function () {
  30653. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30654. this.delayLoad();
  30655. return false;
  30656. }
  30657. if (this._texture) {
  30658. return this._texture.isReady;
  30659. }
  30660. return false;
  30661. };
  30662. BaseTexture.prototype.getSize = function () {
  30663. if (this._texture) {
  30664. if (this._texture.width) {
  30665. this._cachedSize.width = this._texture.width;
  30666. this._cachedSize.height = this._texture.height;
  30667. return this._cachedSize;
  30668. }
  30669. if (this._texture._size) {
  30670. this._cachedSize.width = this._texture._size;
  30671. this._cachedSize.height = this._texture._size;
  30672. return this._cachedSize;
  30673. }
  30674. }
  30675. return this._cachedSize;
  30676. };
  30677. BaseTexture.prototype.getBaseSize = function () {
  30678. if (!this.isReady() || !this._texture)
  30679. return BABYLON.Size.Zero();
  30680. if (this._texture._size) {
  30681. return new BABYLON.Size(this._texture._size, this._texture._size);
  30682. }
  30683. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30684. };
  30685. BaseTexture.prototype.scale = function (ratio) {
  30686. };
  30687. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30688. get: function () {
  30689. return false;
  30690. },
  30691. enumerable: true,
  30692. configurable: true
  30693. });
  30694. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30695. if (!this._scene) {
  30696. return null;
  30697. }
  30698. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30699. for (var index = 0; index < texturesCache.length; index++) {
  30700. var texturesCacheEntry = texturesCache[index];
  30701. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30702. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30703. texturesCacheEntry.incrementReferences();
  30704. return texturesCacheEntry;
  30705. }
  30706. }
  30707. }
  30708. return null;
  30709. };
  30710. BaseTexture.prototype._rebuild = function () {
  30711. };
  30712. BaseTexture.prototype.delayLoad = function () {
  30713. };
  30714. BaseTexture.prototype.clone = function () {
  30715. return null;
  30716. };
  30717. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30718. get: function () {
  30719. if (!this._texture) {
  30720. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30721. }
  30722. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30723. },
  30724. enumerable: true,
  30725. configurable: true
  30726. });
  30727. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30728. get: function () {
  30729. if (!this._texture) {
  30730. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30731. }
  30732. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30733. },
  30734. enumerable: true,
  30735. configurable: true
  30736. });
  30737. /**
  30738. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30739. * This will returns an RGBA array buffer containing either in values (0-255) or
  30740. * float values (0-1) depending of the underlying buffer type.
  30741. * @param faceIndex The face of the texture to read (in case of cube texture)
  30742. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30743. * @returns The Array buffer containing the pixels data.
  30744. */
  30745. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30746. if (faceIndex === void 0) { faceIndex = 0; }
  30747. if (level === void 0) { level = 0; }
  30748. if (!this._texture) {
  30749. return null;
  30750. }
  30751. var size = this.getSize();
  30752. var width = size.width;
  30753. var height = size.height;
  30754. var scene = this.getScene();
  30755. if (!scene) {
  30756. return null;
  30757. }
  30758. var engine = scene.getEngine();
  30759. if (level != 0) {
  30760. width = width / Math.pow(2, level);
  30761. height = height / Math.pow(2, level);
  30762. width = Math.round(width);
  30763. height = Math.round(height);
  30764. }
  30765. if (this._texture.isCube) {
  30766. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30767. }
  30768. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30769. };
  30770. BaseTexture.prototype.releaseInternalTexture = function () {
  30771. if (this._texture) {
  30772. this._texture.dispose();
  30773. this._texture = null;
  30774. }
  30775. };
  30776. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30777. get: function () {
  30778. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30779. return null;
  30780. }
  30781. if (!this._texture._sphericalPolynomial) {
  30782. this._texture._sphericalPolynomial =
  30783. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30784. }
  30785. return this._texture._sphericalPolynomial;
  30786. },
  30787. set: function (value) {
  30788. if (this._texture) {
  30789. this._texture._sphericalPolynomial = value;
  30790. }
  30791. },
  30792. enumerable: true,
  30793. configurable: true
  30794. });
  30795. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30796. get: function () {
  30797. if (this._texture) {
  30798. return this._texture._lodTextureHigh;
  30799. }
  30800. return null;
  30801. },
  30802. enumerable: true,
  30803. configurable: true
  30804. });
  30805. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30806. get: function () {
  30807. if (this._texture) {
  30808. return this._texture._lodTextureMid;
  30809. }
  30810. return null;
  30811. },
  30812. enumerable: true,
  30813. configurable: true
  30814. });
  30815. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30816. get: function () {
  30817. if (this._texture) {
  30818. return this._texture._lodTextureLow;
  30819. }
  30820. return null;
  30821. },
  30822. enumerable: true,
  30823. configurable: true
  30824. });
  30825. BaseTexture.prototype.dispose = function () {
  30826. if (!this._scene) {
  30827. return;
  30828. }
  30829. // Animations
  30830. this._scene.stopAnimation(this);
  30831. // Remove from scene
  30832. this._scene._removePendingData(this);
  30833. var index = this._scene.textures.indexOf(this);
  30834. if (index >= 0) {
  30835. this._scene.textures.splice(index, 1);
  30836. }
  30837. if (this._texture === undefined) {
  30838. return;
  30839. }
  30840. // Release
  30841. this.releaseInternalTexture();
  30842. // Callback
  30843. this.onDisposeObservable.notifyObservers(this);
  30844. this.onDisposeObservable.clear();
  30845. };
  30846. BaseTexture.prototype.serialize = function () {
  30847. if (!this.name) {
  30848. return null;
  30849. }
  30850. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30851. // Animations
  30852. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30853. return serializationObject;
  30854. };
  30855. BaseTexture.WhenAllReady = function (textures, callback) {
  30856. var numRemaining = textures.length;
  30857. if (numRemaining === 0) {
  30858. callback();
  30859. return;
  30860. }
  30861. var _loop_1 = function () {
  30862. texture = textures[i];
  30863. if (texture.isReady()) {
  30864. if (--numRemaining === 0) {
  30865. callback();
  30866. }
  30867. }
  30868. else {
  30869. onLoadObservable = texture.onLoadObservable;
  30870. var onLoadCallback_1 = function () {
  30871. onLoadObservable.removeCallback(onLoadCallback_1);
  30872. if (--numRemaining === 0) {
  30873. callback();
  30874. }
  30875. };
  30876. onLoadObservable.add(onLoadCallback_1);
  30877. }
  30878. };
  30879. var texture, onLoadObservable;
  30880. for (var i = 0; i < textures.length; i++) {
  30881. _loop_1();
  30882. }
  30883. };
  30884. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30885. __decorate([
  30886. BABYLON.serialize()
  30887. ], BaseTexture.prototype, "name", void 0);
  30888. __decorate([
  30889. BABYLON.serialize("hasAlpha")
  30890. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30891. __decorate([
  30892. BABYLON.serialize()
  30893. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30894. __decorate([
  30895. BABYLON.serialize()
  30896. ], BaseTexture.prototype, "level", void 0);
  30897. __decorate([
  30898. BABYLON.serialize()
  30899. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30900. __decorate([
  30901. BABYLON.serialize("coordinatesMode")
  30902. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30903. __decorate([
  30904. BABYLON.serialize()
  30905. ], BaseTexture.prototype, "wrapU", void 0);
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], BaseTexture.prototype, "wrapV", void 0);
  30909. __decorate([
  30910. BABYLON.serialize()
  30911. ], BaseTexture.prototype, "wrapR", void 0);
  30912. __decorate([
  30913. BABYLON.serialize()
  30914. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30915. __decorate([
  30916. BABYLON.serialize()
  30917. ], BaseTexture.prototype, "isCube", void 0);
  30918. __decorate([
  30919. BABYLON.serialize()
  30920. ], BaseTexture.prototype, "is3D", void 0);
  30921. __decorate([
  30922. BABYLON.serialize()
  30923. ], BaseTexture.prototype, "gammaSpace", void 0);
  30924. __decorate([
  30925. BABYLON.serialize()
  30926. ], BaseTexture.prototype, "invertZ", void 0);
  30927. __decorate([
  30928. BABYLON.serialize()
  30929. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30930. __decorate([
  30931. BABYLON.serialize()
  30932. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30933. __decorate([
  30934. BABYLON.serialize()
  30935. ], BaseTexture.prototype, "lodGenerationScale", null);
  30936. __decorate([
  30937. BABYLON.serialize()
  30938. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30939. return BaseTexture;
  30940. }());
  30941. BABYLON.BaseTexture = BaseTexture;
  30942. })(BABYLON || (BABYLON = {}));
  30943. //# sourceMappingURL=babylon.baseTexture.js.map
  30944. var BABYLON;
  30945. (function (BABYLON) {
  30946. var Texture = /** @class */ (function (_super) {
  30947. __extends(Texture, _super);
  30948. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30949. if (noMipmap === void 0) { noMipmap = false; }
  30950. if (invertY === void 0) { invertY = true; }
  30951. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30952. if (onLoad === void 0) { onLoad = null; }
  30953. if (onError === void 0) { onError = null; }
  30954. if (buffer === void 0) { buffer = null; }
  30955. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30956. var _this = _super.call(this, scene) || this;
  30957. _this.uOffset = 0;
  30958. _this.vOffset = 0;
  30959. _this.uScale = 1.0;
  30960. _this.vScale = 1.0;
  30961. _this.uAng = 0;
  30962. _this.vAng = 0;
  30963. _this.wAng = 0;
  30964. /**
  30965. * Defines the center of rotation (U)
  30966. */
  30967. _this.uRotationCenter = 0.5;
  30968. /**
  30969. * Defines the center of rotation (V)
  30970. */
  30971. _this.vRotationCenter = 0.5;
  30972. /**
  30973. * Defines the center of rotation (W)
  30974. */
  30975. _this.wRotationCenter = 0.5;
  30976. _this._isBlocking = true;
  30977. _this.name = url || "";
  30978. _this.url = url;
  30979. _this._noMipmap = noMipmap;
  30980. _this._invertY = invertY;
  30981. _this._samplingMode = samplingMode;
  30982. _this._buffer = buffer;
  30983. _this._deleteBuffer = deleteBuffer;
  30984. if (format) {
  30985. _this._format = format;
  30986. }
  30987. scene = _this.getScene();
  30988. if (!scene) {
  30989. return _this;
  30990. }
  30991. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30992. var load = function () {
  30993. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30994. _this.onLoadObservable.notifyObservers(_this);
  30995. }
  30996. if (onLoad) {
  30997. onLoad();
  30998. }
  30999. if (!_this.isBlocking && scene) {
  31000. scene.resetCachedMaterial();
  31001. }
  31002. };
  31003. if (!_this.url) {
  31004. _this._delayedOnLoad = load;
  31005. _this._delayedOnError = onError;
  31006. return _this;
  31007. }
  31008. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31009. if (!_this._texture) {
  31010. if (!scene.useDelayedTextureLoading) {
  31011. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31012. if (deleteBuffer) {
  31013. delete _this._buffer;
  31014. }
  31015. }
  31016. else {
  31017. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31018. _this._delayedOnLoad = load;
  31019. _this._delayedOnError = onError;
  31020. }
  31021. }
  31022. else {
  31023. if (_this._texture.isReady) {
  31024. BABYLON.Tools.SetImmediate(function () { return load(); });
  31025. }
  31026. else {
  31027. _this._texture.onLoadedObservable.add(load);
  31028. }
  31029. }
  31030. return _this;
  31031. }
  31032. Object.defineProperty(Texture.prototype, "noMipmap", {
  31033. get: function () {
  31034. return this._noMipmap;
  31035. },
  31036. enumerable: true,
  31037. configurable: true
  31038. });
  31039. Object.defineProperty(Texture.prototype, "isBlocking", {
  31040. get: function () {
  31041. return this._isBlocking;
  31042. },
  31043. set: function (value) {
  31044. this._isBlocking = value;
  31045. },
  31046. enumerable: true,
  31047. configurable: true
  31048. });
  31049. Object.defineProperty(Texture.prototype, "samplingMode", {
  31050. get: function () {
  31051. return this._samplingMode;
  31052. },
  31053. enumerable: true,
  31054. configurable: true
  31055. });
  31056. /**
  31057. * Update the url (and optional buffer) of this texture if url was null during construction.
  31058. * @param url the url of the texture
  31059. * @param buffer the buffer of the texture (defaults to null)
  31060. */
  31061. Texture.prototype.updateURL = function (url, buffer) {
  31062. if (buffer === void 0) { buffer = null; }
  31063. if (this.url) {
  31064. throw new Error("URL is already set");
  31065. }
  31066. this.url = url;
  31067. this._buffer = buffer;
  31068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31069. this.delayLoad();
  31070. };
  31071. Texture.prototype.delayLoad = function () {
  31072. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31073. return;
  31074. }
  31075. var scene = this.getScene();
  31076. if (!scene) {
  31077. return;
  31078. }
  31079. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31080. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31081. if (!this._texture) {
  31082. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31083. if (this._deleteBuffer) {
  31084. delete this._buffer;
  31085. }
  31086. }
  31087. else {
  31088. if (this._delayedOnLoad) {
  31089. if (this._texture.isReady) {
  31090. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31091. }
  31092. else {
  31093. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31094. }
  31095. }
  31096. }
  31097. this._delayedOnLoad = null;
  31098. this._delayedOnError = null;
  31099. };
  31100. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31101. if (!this._texture) {
  31102. return;
  31103. }
  31104. var scene = this.getScene();
  31105. if (!scene) {
  31106. return;
  31107. }
  31108. this._samplingMode = samplingMode;
  31109. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31110. };
  31111. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31112. x *= this.uScale;
  31113. y *= this.vScale;
  31114. x -= this.uRotationCenter * this.uScale;
  31115. y -= this.vRotationCenter * this.vScale;
  31116. z -= this.wRotationCenter;
  31117. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31118. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31119. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31120. t.z += this.wRotationCenter;
  31121. };
  31122. Texture.prototype.getTextureMatrix = function () {
  31123. var _this = this;
  31124. if (this.uOffset === this._cachedUOffset &&
  31125. this.vOffset === this._cachedVOffset &&
  31126. this.uScale === this._cachedUScale &&
  31127. this.vScale === this._cachedVScale &&
  31128. this.uAng === this._cachedUAng &&
  31129. this.vAng === this._cachedVAng &&
  31130. this.wAng === this._cachedWAng) {
  31131. return this._cachedTextureMatrix;
  31132. }
  31133. this._cachedUOffset = this.uOffset;
  31134. this._cachedVOffset = this.vOffset;
  31135. this._cachedUScale = this.uScale;
  31136. this._cachedVScale = this.vScale;
  31137. this._cachedUAng = this.uAng;
  31138. this._cachedVAng = this.vAng;
  31139. this._cachedWAng = this.wAng;
  31140. if (!this._cachedTextureMatrix) {
  31141. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31142. this._rowGenerationMatrix = new BABYLON.Matrix();
  31143. this._t0 = BABYLON.Vector3.Zero();
  31144. this._t1 = BABYLON.Vector3.Zero();
  31145. this._t2 = BABYLON.Vector3.Zero();
  31146. }
  31147. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31148. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31149. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31150. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31151. this._t1.subtractInPlace(this._t0);
  31152. this._t2.subtractInPlace(this._t0);
  31153. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31154. this._cachedTextureMatrix.m[0] = this._t1.x;
  31155. this._cachedTextureMatrix.m[1] = this._t1.y;
  31156. this._cachedTextureMatrix.m[2] = this._t1.z;
  31157. this._cachedTextureMatrix.m[4] = this._t2.x;
  31158. this._cachedTextureMatrix.m[5] = this._t2.y;
  31159. this._cachedTextureMatrix.m[6] = this._t2.z;
  31160. this._cachedTextureMatrix.m[8] = this._t0.x;
  31161. this._cachedTextureMatrix.m[9] = this._t0.y;
  31162. this._cachedTextureMatrix.m[10] = this._t0.z;
  31163. var scene = this.getScene();
  31164. if (!scene) {
  31165. return this._cachedTextureMatrix;
  31166. }
  31167. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31168. return mat.hasTexture(_this);
  31169. });
  31170. return this._cachedTextureMatrix;
  31171. };
  31172. Texture.prototype.getReflectionTextureMatrix = function () {
  31173. var _this = this;
  31174. var scene = this.getScene();
  31175. if (!scene) {
  31176. return this._cachedTextureMatrix;
  31177. }
  31178. if (this.uOffset === this._cachedUOffset &&
  31179. this.vOffset === this._cachedVOffset &&
  31180. this.uScale === this._cachedUScale &&
  31181. this.vScale === this._cachedVScale &&
  31182. this.coordinatesMode === this._cachedCoordinatesMode) {
  31183. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31184. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31185. return this._cachedTextureMatrix;
  31186. }
  31187. }
  31188. else {
  31189. return this._cachedTextureMatrix;
  31190. }
  31191. }
  31192. if (!this._cachedTextureMatrix) {
  31193. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31194. }
  31195. if (!this._projectionModeMatrix) {
  31196. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31197. }
  31198. this._cachedUOffset = this.uOffset;
  31199. this._cachedVOffset = this.vOffset;
  31200. this._cachedUScale = this.uScale;
  31201. this._cachedVScale = this.vScale;
  31202. this._cachedCoordinatesMode = this.coordinatesMode;
  31203. switch (this.coordinatesMode) {
  31204. case Texture.PLANAR_MODE:
  31205. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31206. this._cachedTextureMatrix[0] = this.uScale;
  31207. this._cachedTextureMatrix[5] = this.vScale;
  31208. this._cachedTextureMatrix[12] = this.uOffset;
  31209. this._cachedTextureMatrix[13] = this.vOffset;
  31210. break;
  31211. case Texture.PROJECTION_MODE:
  31212. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31213. this._projectionModeMatrix.m[0] = 0.5;
  31214. this._projectionModeMatrix.m[5] = -0.5;
  31215. this._projectionModeMatrix.m[10] = 0.0;
  31216. this._projectionModeMatrix.m[12] = 0.5;
  31217. this._projectionModeMatrix.m[13] = 0.5;
  31218. this._projectionModeMatrix.m[14] = 1.0;
  31219. this._projectionModeMatrix.m[15] = 1.0;
  31220. var projectionMatrix = scene.getProjectionMatrix();
  31221. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31222. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31223. break;
  31224. default:
  31225. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31226. break;
  31227. }
  31228. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31229. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31230. });
  31231. return this._cachedTextureMatrix;
  31232. };
  31233. Texture.prototype.clone = function () {
  31234. var _this = this;
  31235. return BABYLON.SerializationHelper.Clone(function () {
  31236. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31237. }, this);
  31238. };
  31239. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31240. get: function () {
  31241. if (!this._onLoadObservable) {
  31242. this._onLoadObservable = new BABYLON.Observable();
  31243. }
  31244. return this._onLoadObservable;
  31245. },
  31246. enumerable: true,
  31247. configurable: true
  31248. });
  31249. Texture.prototype.serialize = function () {
  31250. var serializationObject = _super.prototype.serialize.call(this);
  31251. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31252. serializationObject.base64String = this._buffer;
  31253. serializationObject.name = serializationObject.name.replace("data:", "");
  31254. }
  31255. serializationObject.invertY = this._invertY;
  31256. serializationObject.samplingMode = this.samplingMode;
  31257. return serializationObject;
  31258. };
  31259. Texture.prototype.getClassName = function () {
  31260. return "Texture";
  31261. };
  31262. Texture.prototype.dispose = function () {
  31263. _super.prototype.dispose.call(this);
  31264. if (this._onLoadObservable) {
  31265. this._onLoadObservable.clear();
  31266. this._onLoadObservable = null;
  31267. }
  31268. this._delayedOnLoad = null;
  31269. this._delayedOnError = null;
  31270. };
  31271. // Statics
  31272. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31273. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31274. if (onLoad === void 0) { onLoad = null; }
  31275. if (onError === void 0) { onError = null; }
  31276. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31277. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31278. };
  31279. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31280. if (parsedTexture.customType) {
  31281. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31282. // Update Sampling Mode
  31283. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31284. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31285. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31286. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31287. }
  31288. }
  31289. return parsedCustomTexture;
  31290. }
  31291. if (parsedTexture.isCube) {
  31292. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31293. }
  31294. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31295. return null;
  31296. }
  31297. var texture = BABYLON.SerializationHelper.Parse(function () {
  31298. var generateMipMaps = true;
  31299. if (parsedTexture.noMipmap) {
  31300. generateMipMaps = false;
  31301. }
  31302. if (parsedTexture.mirrorPlane) {
  31303. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31304. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31305. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31306. return mirrorTexture;
  31307. }
  31308. else if (parsedTexture.isRenderTarget) {
  31309. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31310. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31311. return renderTargetTexture;
  31312. }
  31313. else {
  31314. var texture;
  31315. if (parsedTexture.base64String) {
  31316. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31317. }
  31318. else {
  31319. var url = rootUrl + parsedTexture.name;
  31320. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31321. url = parsedTexture.url;
  31322. }
  31323. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31324. }
  31325. return texture;
  31326. }
  31327. }, parsedTexture, scene);
  31328. // Update Sampling Mode
  31329. if (parsedTexture.samplingMode) {
  31330. var sampling = parsedTexture.samplingMode;
  31331. if (texture._samplingMode !== sampling) {
  31332. texture.updateSamplingMode(sampling);
  31333. }
  31334. }
  31335. // Animations
  31336. if (parsedTexture.animations) {
  31337. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31338. var parsedAnimation = parsedTexture.animations[animationIndex];
  31339. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31340. }
  31341. }
  31342. return texture;
  31343. };
  31344. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31345. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31346. if (noMipmap === void 0) { noMipmap = false; }
  31347. if (invertY === void 0) { invertY = true; }
  31348. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31349. if (onLoad === void 0) { onLoad = null; }
  31350. if (onError === void 0) { onError = null; }
  31351. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31352. if (name.substr(0, 5) !== "data:") {
  31353. name = "data:" + name;
  31354. }
  31355. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31356. };
  31357. // Constants
  31358. Texture.NEAREST_SAMPLINGMODE = 1;
  31359. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31360. Texture.BILINEAR_SAMPLINGMODE = 2;
  31361. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31362. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31363. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31364. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31365. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31366. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31367. Texture.NEAREST_LINEAR = 7;
  31368. Texture.NEAREST_NEAREST = 8;
  31369. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31370. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31371. Texture.LINEAR_LINEAR = 11;
  31372. Texture.LINEAR_NEAREST = 12;
  31373. Texture.EXPLICIT_MODE = 0;
  31374. Texture.SPHERICAL_MODE = 1;
  31375. Texture.PLANAR_MODE = 2;
  31376. Texture.CUBIC_MODE = 3;
  31377. Texture.PROJECTION_MODE = 4;
  31378. Texture.SKYBOX_MODE = 5;
  31379. Texture.INVCUBIC_MODE = 6;
  31380. Texture.EQUIRECTANGULAR_MODE = 7;
  31381. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31382. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31383. Texture.CLAMP_ADDRESSMODE = 0;
  31384. Texture.WRAP_ADDRESSMODE = 1;
  31385. Texture.MIRROR_ADDRESSMODE = 2;
  31386. /**
  31387. * 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
  31388. */
  31389. Texture.UseSerializedUrlIfAny = false;
  31390. __decorate([
  31391. BABYLON.serialize()
  31392. ], Texture.prototype, "url", void 0);
  31393. __decorate([
  31394. BABYLON.serialize()
  31395. ], Texture.prototype, "uOffset", void 0);
  31396. __decorate([
  31397. BABYLON.serialize()
  31398. ], Texture.prototype, "vOffset", void 0);
  31399. __decorate([
  31400. BABYLON.serialize()
  31401. ], Texture.prototype, "uScale", void 0);
  31402. __decorate([
  31403. BABYLON.serialize()
  31404. ], Texture.prototype, "vScale", void 0);
  31405. __decorate([
  31406. BABYLON.serialize()
  31407. ], Texture.prototype, "uAng", void 0);
  31408. __decorate([
  31409. BABYLON.serialize()
  31410. ], Texture.prototype, "vAng", void 0);
  31411. __decorate([
  31412. BABYLON.serialize()
  31413. ], Texture.prototype, "wAng", void 0);
  31414. __decorate([
  31415. BABYLON.serialize()
  31416. ], Texture.prototype, "uRotationCenter", void 0);
  31417. __decorate([
  31418. BABYLON.serialize()
  31419. ], Texture.prototype, "vRotationCenter", void 0);
  31420. __decorate([
  31421. BABYLON.serialize()
  31422. ], Texture.prototype, "wRotationCenter", void 0);
  31423. __decorate([
  31424. BABYLON.serialize()
  31425. ], Texture.prototype, "isBlocking", null);
  31426. return Texture;
  31427. }(BABYLON.BaseTexture));
  31428. BABYLON.Texture = Texture;
  31429. })(BABYLON || (BABYLON = {}));
  31430. //# sourceMappingURL=babylon.texture.js.map
  31431. var BABYLON;
  31432. (function (BABYLON) {
  31433. /**
  31434. * @hidden
  31435. **/
  31436. var _InstancesBatch = /** @class */ (function () {
  31437. function _InstancesBatch() {
  31438. this.mustReturn = false;
  31439. this.visibleInstances = new Array();
  31440. this.renderSelf = new Array();
  31441. }
  31442. return _InstancesBatch;
  31443. }());
  31444. BABYLON._InstancesBatch = _InstancesBatch;
  31445. var Mesh = /** @class */ (function (_super) {
  31446. __extends(Mesh, _super);
  31447. /**
  31448. * @constructor
  31449. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31450. * @param {Scene} scene The scene to add this mesh to.
  31451. * @param {Node} parent The parent of this mesh, if it has one
  31452. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31453. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31454. * When false, achieved by calling a clone(), also passing False.
  31455. * This will make creation of children, recursive.
  31456. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31457. */
  31458. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31459. if (scene === void 0) { scene = null; }
  31460. if (parent === void 0) { parent = null; }
  31461. if (source === void 0) { source = null; }
  31462. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31463. var _this = _super.call(this, name, scene) || this;
  31464. // Events
  31465. /**
  31466. * An event triggered before rendering the mesh
  31467. */
  31468. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31469. /**
  31470. * An event triggered after rendering the mesh
  31471. */
  31472. _this.onAfterRenderObservable = new BABYLON.Observable();
  31473. /**
  31474. * An event triggered before drawing the mesh
  31475. */
  31476. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31477. // Members
  31478. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31479. _this.instances = new Array();
  31480. _this._LODLevels = new Array();
  31481. _this._visibleInstances = {};
  31482. _this._renderIdForInstances = new Array();
  31483. _this._batchCache = new _InstancesBatch();
  31484. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31485. // Use by builder only to know what orientation were the mesh build in.
  31486. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31487. _this.overrideMaterialSideOrientation = null;
  31488. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31489. // Will be used to save a source mesh reference, If any
  31490. _this._source = null;
  31491. scene = _this.getScene();
  31492. if (source) {
  31493. // Geometry
  31494. if (source._geometry) {
  31495. source._geometry.applyToMesh(_this);
  31496. }
  31497. // Deep copy
  31498. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31499. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31500. // Source mesh
  31501. _this._source = source;
  31502. // Metadata
  31503. if (source.metadata && source.metadata.clone) {
  31504. _this.metadata = source.metadata.clone();
  31505. }
  31506. else {
  31507. _this.metadata = source.metadata;
  31508. }
  31509. // Tags
  31510. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31511. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31512. }
  31513. // Parent
  31514. _this.parent = source.parent;
  31515. // Pivot
  31516. _this.setPivotMatrix(source.getPivotMatrix());
  31517. _this.id = name + "." + source.id;
  31518. // Material
  31519. _this.material = source.material;
  31520. var index;
  31521. if (!doNotCloneChildren) {
  31522. // Children
  31523. var directDescendants = source.getDescendants(true);
  31524. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31525. var child = directDescendants[index_1];
  31526. if (child.clone) {
  31527. child.clone(name + "." + child.name, _this);
  31528. }
  31529. }
  31530. }
  31531. // Physics clone
  31532. var physicsEngine = _this.getScene().getPhysicsEngine();
  31533. if (clonePhysicsImpostor && physicsEngine) {
  31534. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31535. if (impostor) {
  31536. _this.physicsImpostor = impostor.clone(_this);
  31537. }
  31538. }
  31539. // Particles
  31540. for (index = 0; index < scene.particleSystems.length; index++) {
  31541. var system = scene.particleSystems[index];
  31542. if (system.emitter === source) {
  31543. system.clone(system.name, _this);
  31544. }
  31545. }
  31546. _this.refreshBoundingInfo();
  31547. _this.computeWorldMatrix(true);
  31548. }
  31549. // Parent
  31550. if (parent !== null) {
  31551. _this.parent = parent;
  31552. }
  31553. return _this;
  31554. }
  31555. Object.defineProperty(Mesh, "FRONTSIDE", {
  31556. /**
  31557. * Mesh side orientation : usually the external or front surface
  31558. */
  31559. get: function () {
  31560. return Mesh._FRONTSIDE;
  31561. },
  31562. enumerable: true,
  31563. configurable: true
  31564. });
  31565. Object.defineProperty(Mesh, "BACKSIDE", {
  31566. /**
  31567. * Mesh side orientation : usually the internal or back surface
  31568. */
  31569. get: function () {
  31570. return Mesh._BACKSIDE;
  31571. },
  31572. enumerable: true,
  31573. configurable: true
  31574. });
  31575. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31576. /**
  31577. * Mesh side orientation : both internal and external or front and back surfaces
  31578. */
  31579. get: function () {
  31580. return Mesh._DOUBLESIDE;
  31581. },
  31582. enumerable: true,
  31583. configurable: true
  31584. });
  31585. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31586. /**
  31587. * Mesh side orientation : by default, `FRONTSIDE`
  31588. */
  31589. get: function () {
  31590. return Mesh._DEFAULTSIDE;
  31591. },
  31592. enumerable: true,
  31593. configurable: true
  31594. });
  31595. Object.defineProperty(Mesh, "NO_CAP", {
  31596. /**
  31597. * Mesh cap setting : no cap
  31598. */
  31599. get: function () {
  31600. return Mesh._NO_CAP;
  31601. },
  31602. enumerable: true,
  31603. configurable: true
  31604. });
  31605. Object.defineProperty(Mesh, "CAP_START", {
  31606. /**
  31607. * Mesh cap setting : one cap at the beginning of the mesh
  31608. */
  31609. get: function () {
  31610. return Mesh._CAP_START;
  31611. },
  31612. enumerable: true,
  31613. configurable: true
  31614. });
  31615. Object.defineProperty(Mesh, "CAP_END", {
  31616. /**
  31617. * Mesh cap setting : one cap at the end of the mesh
  31618. */
  31619. get: function () {
  31620. return Mesh._CAP_END;
  31621. },
  31622. enumerable: true,
  31623. configurable: true
  31624. });
  31625. Object.defineProperty(Mesh, "CAP_ALL", {
  31626. /**
  31627. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31628. */
  31629. get: function () {
  31630. return Mesh._CAP_ALL;
  31631. },
  31632. enumerable: true,
  31633. configurable: true
  31634. });
  31635. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31636. set: function (callback) {
  31637. if (this._onBeforeDrawObserver) {
  31638. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31639. }
  31640. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31641. },
  31642. enumerable: true,
  31643. configurable: true
  31644. });
  31645. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31646. get: function () {
  31647. return this._morphTargetManager;
  31648. },
  31649. set: function (value) {
  31650. if (this._morphTargetManager === value) {
  31651. return;
  31652. }
  31653. this._morphTargetManager = value;
  31654. this._syncGeometryWithMorphTargetManager();
  31655. },
  31656. enumerable: true,
  31657. configurable: true
  31658. });
  31659. Object.defineProperty(Mesh.prototype, "source", {
  31660. get: function () {
  31661. return this._source;
  31662. },
  31663. enumerable: true,
  31664. configurable: true
  31665. });
  31666. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31667. get: function () {
  31668. return this._unIndexed;
  31669. },
  31670. set: function (value) {
  31671. if (this._unIndexed !== value) {
  31672. this._unIndexed = value;
  31673. this._markSubMeshesAsAttributesDirty();
  31674. }
  31675. },
  31676. enumerable: true,
  31677. configurable: true
  31678. });
  31679. // Methods
  31680. /**
  31681. * Returns the string "Mesh".
  31682. */
  31683. Mesh.prototype.getClassName = function () {
  31684. return "Mesh";
  31685. };
  31686. /**
  31687. * Returns a string.
  31688. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31689. */
  31690. Mesh.prototype.toString = function (fullDetails) {
  31691. var ret = _super.prototype.toString.call(this, fullDetails);
  31692. ret += ", n vertices: " + this.getTotalVertices();
  31693. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31694. if (this.animations) {
  31695. for (var i = 0; i < this.animations.length; i++) {
  31696. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31697. }
  31698. }
  31699. if (fullDetails) {
  31700. if (this._geometry) {
  31701. var ib = this.getIndices();
  31702. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31703. if (vb && ib) {
  31704. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31705. }
  31706. }
  31707. else {
  31708. ret += ", flat shading: UNKNOWN";
  31709. }
  31710. }
  31711. return ret;
  31712. };
  31713. Mesh.prototype._unBindEffect = function () {
  31714. _super.prototype._unBindEffect.call(this);
  31715. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31716. var instance = _a[_i];
  31717. instance._unBindEffect();
  31718. }
  31719. };
  31720. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31721. /**
  31722. * True if the mesh has some Levels Of Details (LOD).
  31723. * Returns a boolean.
  31724. */
  31725. get: function () {
  31726. return this._LODLevels.length > 0;
  31727. },
  31728. enumerable: true,
  31729. configurable: true
  31730. });
  31731. /**
  31732. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31733. * @returns an array of {BABYLON.MeshLODLevel}
  31734. */
  31735. Mesh.prototype.getLODLevels = function () {
  31736. return this._LODLevels;
  31737. };
  31738. Mesh.prototype._sortLODLevels = function () {
  31739. this._LODLevels.sort(function (a, b) {
  31740. if (a.distance < b.distance) {
  31741. return 1;
  31742. }
  31743. if (a.distance > b.distance) {
  31744. return -1;
  31745. }
  31746. return 0;
  31747. });
  31748. };
  31749. /**
  31750. * Add a mesh as LOD level triggered at the given distance.
  31751. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31752. * @param distance The distance from the center of the object to show this level
  31753. * @param mesh The mesh to be added as LOD level (can be null)
  31754. * @return This mesh (for chaining)
  31755. */
  31756. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31757. if (mesh && mesh._masterMesh) {
  31758. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31759. return this;
  31760. }
  31761. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31762. this._LODLevels.push(level);
  31763. if (mesh) {
  31764. mesh._masterMesh = this;
  31765. }
  31766. this._sortLODLevels();
  31767. return this;
  31768. };
  31769. /**
  31770. * Returns the LOD level mesh at the passed distance or null if not found.
  31771. * It is related to the method `addLODLevel(distance, mesh)`.
  31772. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31773. * Returns an object Mesh or `null`.
  31774. */
  31775. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31776. for (var index = 0; index < this._LODLevels.length; index++) {
  31777. var level = this._LODLevels[index];
  31778. if (level.distance === distance) {
  31779. return level.mesh;
  31780. }
  31781. }
  31782. return null;
  31783. };
  31784. /**
  31785. * Remove a mesh from the LOD array
  31786. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31787. * @param {Mesh} mesh The mesh to be removed.
  31788. * @return {Mesh} This mesh (for chaining)
  31789. */
  31790. Mesh.prototype.removeLODLevel = function (mesh) {
  31791. for (var index = 0; index < this._LODLevels.length; index++) {
  31792. if (this._LODLevels[index].mesh === mesh) {
  31793. this._LODLevels.splice(index, 1);
  31794. if (mesh) {
  31795. mesh._masterMesh = null;
  31796. }
  31797. }
  31798. }
  31799. this._sortLODLevels();
  31800. return this;
  31801. };
  31802. /**
  31803. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31804. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31805. */
  31806. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31807. if (!this._LODLevels || this._LODLevels.length === 0) {
  31808. return this;
  31809. }
  31810. var bSphere;
  31811. if (boundingSphere) {
  31812. bSphere = boundingSphere;
  31813. }
  31814. else {
  31815. var boundingInfo = this.getBoundingInfo();
  31816. bSphere = boundingInfo.boundingSphere;
  31817. }
  31818. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31819. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31820. if (this.onLODLevelSelection) {
  31821. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31822. }
  31823. return this;
  31824. }
  31825. for (var index = 0; index < this._LODLevels.length; index++) {
  31826. var level = this._LODLevels[index];
  31827. if (level.distance < distanceToCamera) {
  31828. if (level.mesh) {
  31829. level.mesh._preActivate();
  31830. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31831. }
  31832. if (this.onLODLevelSelection) {
  31833. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31834. }
  31835. return level.mesh;
  31836. }
  31837. }
  31838. if (this.onLODLevelSelection) {
  31839. this.onLODLevelSelection(distanceToCamera, this, this);
  31840. }
  31841. return this;
  31842. };
  31843. Object.defineProperty(Mesh.prototype, "geometry", {
  31844. /**
  31845. * Returns the mesh internal Geometry object.
  31846. */
  31847. get: function () {
  31848. return this._geometry;
  31849. },
  31850. enumerable: true,
  31851. configurable: true
  31852. });
  31853. /**
  31854. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31855. */
  31856. Mesh.prototype.getTotalVertices = function () {
  31857. if (this._geometry === null || this._geometry === undefined) {
  31858. return 0;
  31859. }
  31860. return this._geometry.getTotalVertices();
  31861. };
  31862. /**
  31863. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31864. * 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.
  31865. * You can force the copy with forceCopy === true
  31866. * Returns null if the mesh has no geometry or no vertex buffer.
  31867. * Possible `kind` values :
  31868. * - BABYLON.VertexBuffer.PositionKind
  31869. * - BABYLON.VertexBuffer.UVKind
  31870. * - BABYLON.VertexBuffer.UV2Kind
  31871. * - BABYLON.VertexBuffer.UV3Kind
  31872. * - BABYLON.VertexBuffer.UV4Kind
  31873. * - BABYLON.VertexBuffer.UV5Kind
  31874. * - BABYLON.VertexBuffer.UV6Kind
  31875. * - BABYLON.VertexBuffer.ColorKind
  31876. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31877. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31878. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31879. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31880. */
  31881. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31882. if (!this._geometry) {
  31883. return null;
  31884. }
  31885. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31886. };
  31887. /**
  31888. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31889. * Returns `null` if the mesh has no geometry.
  31890. * Possible `kind` values :
  31891. * - BABYLON.VertexBuffer.PositionKind
  31892. * - BABYLON.VertexBuffer.UVKind
  31893. * - BABYLON.VertexBuffer.UV2Kind
  31894. * - BABYLON.VertexBuffer.UV3Kind
  31895. * - BABYLON.VertexBuffer.UV4Kind
  31896. * - BABYLON.VertexBuffer.UV5Kind
  31897. * - BABYLON.VertexBuffer.UV6Kind
  31898. * - BABYLON.VertexBuffer.ColorKind
  31899. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31900. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31901. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31902. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31903. */
  31904. Mesh.prototype.getVertexBuffer = function (kind) {
  31905. if (!this._geometry) {
  31906. return null;
  31907. }
  31908. return this._geometry.getVertexBuffer(kind);
  31909. };
  31910. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31911. if (!this._geometry) {
  31912. if (this._delayInfo) {
  31913. return this._delayInfo.indexOf(kind) !== -1;
  31914. }
  31915. return false;
  31916. }
  31917. return this._geometry.isVerticesDataPresent(kind);
  31918. };
  31919. /**
  31920. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31921. * Possible `kind` values :
  31922. * - BABYLON.VertexBuffer.PositionKind
  31923. * - BABYLON.VertexBuffer.UVKind
  31924. * - BABYLON.VertexBuffer.UV2Kind
  31925. * - BABYLON.VertexBuffer.UV3Kind
  31926. * - BABYLON.VertexBuffer.UV4Kind
  31927. * - BABYLON.VertexBuffer.UV5Kind
  31928. * - BABYLON.VertexBuffer.UV6Kind
  31929. * - BABYLON.VertexBuffer.ColorKind
  31930. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31931. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31932. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31933. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31934. */
  31935. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31936. if (!this._geometry) {
  31937. if (this._delayInfo) {
  31938. return this._delayInfo.indexOf(kind) !== -1;
  31939. }
  31940. return false;
  31941. }
  31942. return this._geometry.isVertexBufferUpdatable(kind);
  31943. };
  31944. /**
  31945. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31946. * Possible `kind` values :
  31947. * - BABYLON.VertexBuffer.PositionKind
  31948. * - BABYLON.VertexBuffer.UVKind
  31949. * - BABYLON.VertexBuffer.UV2Kind
  31950. * - BABYLON.VertexBuffer.UV3Kind
  31951. * - BABYLON.VertexBuffer.UV4Kind
  31952. * - BABYLON.VertexBuffer.UV5Kind
  31953. * - BABYLON.VertexBuffer.UV6Kind
  31954. * - BABYLON.VertexBuffer.ColorKind
  31955. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31956. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31957. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31958. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31959. */
  31960. Mesh.prototype.getVerticesDataKinds = function () {
  31961. if (!this._geometry) {
  31962. var result = new Array();
  31963. if (this._delayInfo) {
  31964. this._delayInfo.forEach(function (kind, index, array) {
  31965. result.push(kind);
  31966. });
  31967. }
  31968. return result;
  31969. }
  31970. return this._geometry.getVerticesDataKinds();
  31971. };
  31972. /**
  31973. * Returns a positive integer : the total number of indices in this mesh geometry.
  31974. * Returns zero if the mesh has no geometry.
  31975. */
  31976. Mesh.prototype.getTotalIndices = function () {
  31977. if (!this._geometry) {
  31978. return 0;
  31979. }
  31980. return this._geometry.getTotalIndices();
  31981. };
  31982. /**
  31983. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31984. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31985. * Returns an empty array if the mesh has no geometry.
  31986. */
  31987. Mesh.prototype.getIndices = function (copyWhenShared) {
  31988. if (!this._geometry) {
  31989. return [];
  31990. }
  31991. return this._geometry.getIndices(copyWhenShared);
  31992. };
  31993. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31994. get: function () {
  31995. return this._masterMesh !== null && this._masterMesh !== undefined;
  31996. },
  31997. enumerable: true,
  31998. configurable: true
  31999. });
  32000. /**
  32001. * Determine if the current mesh is ready to be rendered
  32002. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32003. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32004. * @returns true if all associated assets are ready (material, textures, shaders)
  32005. */
  32006. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32007. if (completeCheck === void 0) { completeCheck = false; }
  32008. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32009. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32010. return false;
  32011. }
  32012. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32013. return false;
  32014. }
  32015. if (!this.subMeshes || this.subMeshes.length === 0) {
  32016. return true;
  32017. }
  32018. if (!completeCheck) {
  32019. return true;
  32020. }
  32021. var engine = this.getEngine();
  32022. var scene = this.getScene();
  32023. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32024. this.computeWorldMatrix();
  32025. var mat = this.material || scene.defaultMaterial;
  32026. if (mat) {
  32027. if (mat.storeEffectOnSubMeshes) {
  32028. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32029. var subMesh = _a[_i];
  32030. var effectiveMaterial = subMesh.getMaterial();
  32031. if (effectiveMaterial) {
  32032. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32033. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32034. return false;
  32035. }
  32036. }
  32037. else {
  32038. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32039. return false;
  32040. }
  32041. }
  32042. }
  32043. }
  32044. }
  32045. else {
  32046. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32047. return false;
  32048. }
  32049. }
  32050. }
  32051. // Shadows
  32052. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32053. var light = _c[_b];
  32054. var generator = light.getShadowGenerator();
  32055. if (generator) {
  32056. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32057. var subMesh = _e[_d];
  32058. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32059. return false;
  32060. }
  32061. }
  32062. }
  32063. }
  32064. // LOD
  32065. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32066. var lod = _g[_f];
  32067. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32068. return false;
  32069. }
  32070. }
  32071. return true;
  32072. };
  32073. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32074. /**
  32075. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32076. * This property is pertinent only for updatable parametric shapes.
  32077. */
  32078. get: function () {
  32079. return this._areNormalsFrozen;
  32080. },
  32081. enumerable: true,
  32082. configurable: true
  32083. });
  32084. /**
  32085. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32086. * It has no effect at all on other shapes.
  32087. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32088. * Returns the Mesh.
  32089. */
  32090. Mesh.prototype.freezeNormals = function () {
  32091. this._areNormalsFrozen = true;
  32092. return this;
  32093. };
  32094. /**
  32095. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32096. * It has no effect at all on other shapes.
  32097. * It reactivates the mesh normals computation if it was previously frozen.
  32098. * Returns the Mesh.
  32099. */
  32100. Mesh.prototype.unfreezeNormals = function () {
  32101. this._areNormalsFrozen = false;
  32102. return this;
  32103. };
  32104. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32105. /**
  32106. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32107. */
  32108. set: function (count) {
  32109. this._overridenInstanceCount = count;
  32110. },
  32111. enumerable: true,
  32112. configurable: true
  32113. });
  32114. // Methods
  32115. Mesh.prototype._preActivate = function () {
  32116. var sceneRenderId = this.getScene().getRenderId();
  32117. if (this._preActivateId === sceneRenderId) {
  32118. return this;
  32119. }
  32120. this._preActivateId = sceneRenderId;
  32121. this._visibleInstances = null;
  32122. return this;
  32123. };
  32124. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32125. if (this._visibleInstances) {
  32126. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32127. }
  32128. return this;
  32129. };
  32130. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32131. if (!this._visibleInstances) {
  32132. this._visibleInstances = {};
  32133. this._visibleInstances.defaultRenderId = renderId;
  32134. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32135. }
  32136. if (!this._visibleInstances[renderId]) {
  32137. this._visibleInstances[renderId] = new Array();
  32138. }
  32139. this._visibleInstances[renderId].push(instance);
  32140. return this;
  32141. };
  32142. /**
  32143. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32144. * This means the mesh underlying bounding box and sphere are recomputed.
  32145. * Returns the Mesh.
  32146. */
  32147. Mesh.prototype.refreshBoundingInfo = function () {
  32148. return this._refreshBoundingInfo(false);
  32149. };
  32150. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32151. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32152. return this;
  32153. }
  32154. var data = this._getPositionData(applySkeleton);
  32155. if (data) {
  32156. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32157. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32158. }
  32159. if (this.subMeshes) {
  32160. for (var index = 0; index < this.subMeshes.length; index++) {
  32161. this.subMeshes[index].refreshBoundingInfo();
  32162. }
  32163. }
  32164. this._updateBoundingInfo();
  32165. return this;
  32166. };
  32167. Mesh.prototype._getPositionData = function (applySkeleton) {
  32168. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32169. if (data && applySkeleton && this.skeleton) {
  32170. data = BABYLON.Tools.Slice(data);
  32171. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32172. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32173. if (matricesWeightsData && matricesIndicesData) {
  32174. var needExtras = this.numBoneInfluencers > 4;
  32175. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32176. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32177. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32178. var tempVector = BABYLON.Tmp.Vector3[0];
  32179. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32180. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32181. var matWeightIdx = 0;
  32182. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32183. finalMatrix.reset();
  32184. var inf;
  32185. var weight;
  32186. for (inf = 0; inf < 4; inf++) {
  32187. weight = matricesWeightsData[matWeightIdx + inf];
  32188. if (weight <= 0)
  32189. break;
  32190. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32191. finalMatrix.addToSelf(tempMatrix);
  32192. }
  32193. if (needExtras) {
  32194. for (inf = 0; inf < 4; inf++) {
  32195. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32196. if (weight <= 0)
  32197. break;
  32198. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32199. finalMatrix.addToSelf(tempMatrix);
  32200. }
  32201. }
  32202. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32203. tempVector.toArray(data, index);
  32204. }
  32205. }
  32206. }
  32207. return data;
  32208. };
  32209. Mesh.prototype._createGlobalSubMesh = function (force) {
  32210. var totalVertices = this.getTotalVertices();
  32211. if (!totalVertices || !this.getIndices()) {
  32212. return null;
  32213. }
  32214. // Check if we need to recreate the submeshes
  32215. if (this.subMeshes && this.subMeshes.length > 0) {
  32216. var ib = this.getIndices();
  32217. if (!ib) {
  32218. return null;
  32219. }
  32220. var totalIndices = ib.length;
  32221. var needToRecreate = false;
  32222. if (force) {
  32223. needToRecreate = true;
  32224. }
  32225. else {
  32226. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32227. var submesh = _a[_i];
  32228. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32229. needToRecreate = true;
  32230. break;
  32231. }
  32232. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32233. needToRecreate = true;
  32234. break;
  32235. }
  32236. }
  32237. }
  32238. if (!needToRecreate) {
  32239. return this.subMeshes[0];
  32240. }
  32241. }
  32242. this.releaseSubMeshes();
  32243. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32244. };
  32245. Mesh.prototype.subdivide = function (count) {
  32246. if (count < 1) {
  32247. return;
  32248. }
  32249. var totalIndices = this.getTotalIndices();
  32250. var subdivisionSize = (totalIndices / count) | 0;
  32251. var offset = 0;
  32252. // Ensure that subdivisionSize is a multiple of 3
  32253. while (subdivisionSize % 3 !== 0) {
  32254. subdivisionSize++;
  32255. }
  32256. this.releaseSubMeshes();
  32257. for (var index = 0; index < count; index++) {
  32258. if (offset >= totalIndices) {
  32259. break;
  32260. }
  32261. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32262. offset += subdivisionSize;
  32263. }
  32264. this.synchronizeInstances();
  32265. };
  32266. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32267. if (updatable === void 0) { updatable = false; }
  32268. if (!this._geometry) {
  32269. var vertexData = new BABYLON.VertexData();
  32270. vertexData.set(data, kind);
  32271. var scene = this.getScene();
  32272. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32273. }
  32274. else {
  32275. this._geometry.setVerticesData(kind, data, updatable, stride);
  32276. }
  32277. return this;
  32278. };
  32279. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32280. if (updatable === void 0) { updatable = true; }
  32281. var vb = this.getVertexBuffer(kind);
  32282. if (!vb || vb.isUpdatable() === updatable) {
  32283. return;
  32284. }
  32285. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32286. };
  32287. /**
  32288. * Sets the mesh VertexBuffer.
  32289. * Returns the Mesh.
  32290. */
  32291. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32292. if (!this._geometry) {
  32293. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32294. }
  32295. this._geometry.setVerticesBuffer(buffer);
  32296. return this;
  32297. };
  32298. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32299. if (!this._geometry) {
  32300. return this;
  32301. }
  32302. if (!makeItUnique) {
  32303. this._geometry.updateVerticesData(kind, data, updateExtends);
  32304. }
  32305. else {
  32306. this.makeGeometryUnique();
  32307. this.updateVerticesData(kind, data, updateExtends, false);
  32308. }
  32309. return this;
  32310. };
  32311. /**
  32312. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32313. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32314. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32315. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32316. * Returns the Mesh.
  32317. */
  32318. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32319. if (computeNormals === void 0) { computeNormals = true; }
  32320. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32321. if (!positions) {
  32322. return this;
  32323. }
  32324. positionFunction(positions);
  32325. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32326. if (computeNormals) {
  32327. var indices = this.getIndices();
  32328. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32329. if (!normals) {
  32330. return this;
  32331. }
  32332. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32333. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32334. }
  32335. return this;
  32336. };
  32337. /**
  32338. * Creates a un-shared specific occurence of the geometry for the mesh.
  32339. * Returns the Mesh.
  32340. */
  32341. Mesh.prototype.makeGeometryUnique = function () {
  32342. if (!this._geometry) {
  32343. return this;
  32344. }
  32345. var oldGeometry = this._geometry;
  32346. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32347. oldGeometry.releaseForMesh(this, true);
  32348. geometry.applyToMesh(this);
  32349. return this;
  32350. };
  32351. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32352. if (totalVertices === void 0) { totalVertices = null; }
  32353. if (updatable === void 0) { updatable = false; }
  32354. if (!this._geometry) {
  32355. var vertexData = new BABYLON.VertexData();
  32356. vertexData.indices = indices;
  32357. var scene = this.getScene();
  32358. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32359. }
  32360. else {
  32361. this._geometry.setIndices(indices, totalVertices, updatable);
  32362. }
  32363. return this;
  32364. };
  32365. /**
  32366. * Update the current index buffer
  32367. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32368. * Returns the Mesh.
  32369. */
  32370. Mesh.prototype.updateIndices = function (indices, offset) {
  32371. if (!this._geometry) {
  32372. return this;
  32373. }
  32374. this._geometry.updateIndices(indices, offset);
  32375. return this;
  32376. };
  32377. /**
  32378. * Invert the geometry to move from a right handed system to a left handed one.
  32379. * Returns the Mesh.
  32380. */
  32381. Mesh.prototype.toLeftHanded = function () {
  32382. if (!this._geometry) {
  32383. return this;
  32384. }
  32385. this._geometry.toLeftHanded();
  32386. return this;
  32387. };
  32388. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32389. if (!this._geometry) {
  32390. return this;
  32391. }
  32392. var engine = this.getScene().getEngine();
  32393. // Wireframe
  32394. var indexToBind;
  32395. if (this._unIndexed) {
  32396. indexToBind = null;
  32397. }
  32398. else {
  32399. switch (fillMode) {
  32400. case BABYLON.Material.PointFillMode:
  32401. indexToBind = null;
  32402. break;
  32403. case BABYLON.Material.WireFrameFillMode:
  32404. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32405. break;
  32406. default:
  32407. case BABYLON.Material.TriangleFillMode:
  32408. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32409. break;
  32410. }
  32411. }
  32412. // VBOs
  32413. this._geometry._bind(effect, indexToBind);
  32414. return this;
  32415. };
  32416. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32417. if (alternate === void 0) { alternate = false; }
  32418. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32419. return this;
  32420. }
  32421. this.onBeforeDrawObservable.notifyObservers(this);
  32422. var scene = this.getScene();
  32423. var engine = scene.getEngine();
  32424. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32425. // or triangles as points
  32426. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32427. }
  32428. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32429. // Triangles as wireframe
  32430. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32431. }
  32432. else {
  32433. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32434. }
  32435. if (scene._isAlternateRenderingEnabled && !alternate) {
  32436. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32437. if (!effect || !scene.activeCamera) {
  32438. return this;
  32439. }
  32440. scene._switchToAlternateCameraConfiguration(true);
  32441. this._effectiveMaterial.bindView(effect);
  32442. this._effectiveMaterial.bindViewProjection(effect);
  32443. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32444. this._draw(subMesh, fillMode, instancesCount, true);
  32445. engine.setViewport(scene.activeCamera.viewport);
  32446. scene._switchToAlternateCameraConfiguration(false);
  32447. this._effectiveMaterial.bindView(effect);
  32448. this._effectiveMaterial.bindViewProjection(effect);
  32449. }
  32450. return this;
  32451. };
  32452. /**
  32453. * Registers for this mesh a javascript function called just before the rendering process.
  32454. * This function is passed the current mesh.
  32455. * Return the Mesh.
  32456. */
  32457. Mesh.prototype.registerBeforeRender = function (func) {
  32458. this.onBeforeRenderObservable.add(func);
  32459. return this;
  32460. };
  32461. /**
  32462. * Disposes a previously registered javascript function called before the rendering.
  32463. * This function is passed the current mesh.
  32464. * Returns the Mesh.
  32465. */
  32466. Mesh.prototype.unregisterBeforeRender = function (func) {
  32467. this.onBeforeRenderObservable.removeCallback(func);
  32468. return this;
  32469. };
  32470. /**
  32471. * Registers for this mesh a javascript function called just after the rendering is complete.
  32472. * This function is passed the current mesh.
  32473. * Returns the Mesh.
  32474. */
  32475. Mesh.prototype.registerAfterRender = function (func) {
  32476. this.onAfterRenderObservable.add(func);
  32477. return this;
  32478. };
  32479. /**
  32480. * Disposes a previously registered javascript function called after the rendering.
  32481. * This function is passed the current mesh.
  32482. * Return the Mesh.
  32483. */
  32484. Mesh.prototype.unregisterAfterRender = function (func) {
  32485. this.onAfterRenderObservable.removeCallback(func);
  32486. return this;
  32487. };
  32488. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32489. var scene = this.getScene();
  32490. this._batchCache.mustReturn = false;
  32491. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32492. this._batchCache.visibleInstances[subMeshId] = null;
  32493. if (this._visibleInstances) {
  32494. var currentRenderId = scene.getRenderId();
  32495. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32496. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32497. var selfRenderId = this._renderId;
  32498. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32499. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32500. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32501. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32502. }
  32503. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32504. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32505. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32506. this._batchCache.mustReturn = true;
  32507. return this._batchCache;
  32508. }
  32509. if (currentRenderId !== selfRenderId) {
  32510. this._batchCache.renderSelf[subMeshId] = false;
  32511. }
  32512. }
  32513. this._renderIdForInstances[subMeshId] = currentRenderId;
  32514. }
  32515. return this._batchCache;
  32516. };
  32517. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32518. var visibleInstances = batch.visibleInstances[subMesh._id];
  32519. if (!visibleInstances) {
  32520. return this;
  32521. }
  32522. var matricesCount = visibleInstances.length + 1;
  32523. var bufferSize = matricesCount * 16 * 4;
  32524. var currentInstancesBufferSize = this._instancesBufferSize;
  32525. var instancesBuffer = this._instancesBuffer;
  32526. while (this._instancesBufferSize < bufferSize) {
  32527. this._instancesBufferSize *= 2;
  32528. }
  32529. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32530. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32531. }
  32532. var offset = 0;
  32533. var instancesCount = 0;
  32534. var world = this.getWorldMatrix();
  32535. if (batch.renderSelf[subMesh._id]) {
  32536. world.copyToArray(this._instancesData, offset);
  32537. offset += 16;
  32538. instancesCount++;
  32539. }
  32540. if (visibleInstances) {
  32541. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32542. var instance = visibleInstances[instanceIndex];
  32543. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32544. offset += 16;
  32545. instancesCount++;
  32546. }
  32547. }
  32548. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32549. if (instancesBuffer) {
  32550. instancesBuffer.dispose();
  32551. }
  32552. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32553. this._instancesBuffer = instancesBuffer;
  32554. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32555. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32556. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32557. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32558. }
  32559. else {
  32560. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32561. }
  32562. this._bind(subMesh, effect, fillMode);
  32563. this._draw(subMesh, fillMode, instancesCount);
  32564. engine.unbindInstanceAttributes();
  32565. return this;
  32566. };
  32567. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32568. var scene = this.getScene();
  32569. var engine = scene.getEngine();
  32570. if (hardwareInstancedRendering) {
  32571. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32572. }
  32573. else {
  32574. if (batch.renderSelf[subMesh._id]) {
  32575. // Draw
  32576. if (onBeforeDraw) {
  32577. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32578. }
  32579. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32580. }
  32581. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32582. if (visibleInstancesForSubMesh) {
  32583. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32584. var instance = visibleInstancesForSubMesh[instanceIndex];
  32585. // World
  32586. var world = instance.getWorldMatrix();
  32587. if (onBeforeDraw) {
  32588. onBeforeDraw(true, world, effectiveMaterial);
  32589. }
  32590. // Draw
  32591. this._draw(subMesh, fillMode);
  32592. }
  32593. }
  32594. }
  32595. return this;
  32596. };
  32597. /**
  32598. * Triggers the draw call for the mesh.
  32599. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32600. * Returns the Mesh.
  32601. */
  32602. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32603. this._checkOcclusionQuery();
  32604. if (this._isOccluded) {
  32605. return this;
  32606. }
  32607. var scene = this.getScene();
  32608. // Managing instances
  32609. var batch = this._getInstancesRenderList(subMesh._id);
  32610. if (batch.mustReturn) {
  32611. return this;
  32612. }
  32613. // Checking geometry state
  32614. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32615. return this;
  32616. }
  32617. this.onBeforeRenderObservable.notifyObservers(this);
  32618. var engine = scene.getEngine();
  32619. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32620. // Material
  32621. var material = subMesh.getMaterial();
  32622. if (!material) {
  32623. return this;
  32624. }
  32625. this._effectiveMaterial = material;
  32626. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32627. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32628. return this;
  32629. }
  32630. }
  32631. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32632. return this;
  32633. }
  32634. // Alpha mode
  32635. if (enableAlphaMode) {
  32636. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32637. }
  32638. // Outline - step 1
  32639. var savedDepthWrite = engine.getDepthWrite();
  32640. if (this.renderOutline) {
  32641. engine.setDepthWrite(false);
  32642. scene.getOutlineRenderer().render(subMesh, batch);
  32643. engine.setDepthWrite(savedDepthWrite);
  32644. }
  32645. var effect;
  32646. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32647. effect = subMesh.effect;
  32648. }
  32649. else {
  32650. effect = this._effectiveMaterial.getEffect();
  32651. }
  32652. if (!effect) {
  32653. return this;
  32654. }
  32655. var sideOrientation = this.overrideMaterialSideOrientation;
  32656. if (sideOrientation == null) {
  32657. sideOrientation = this._effectiveMaterial.sideOrientation;
  32658. if (this._getWorldMatrixDeterminant() < 0) {
  32659. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32660. }
  32661. }
  32662. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32663. if (this._effectiveMaterial.forceDepthWrite) {
  32664. engine.setDepthWrite(true);
  32665. }
  32666. // Bind
  32667. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32668. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32669. this._bind(subMesh, effect, fillMode);
  32670. }
  32671. var world = this.getWorldMatrix();
  32672. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32673. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32674. }
  32675. else {
  32676. this._effectiveMaterial.bind(world, this);
  32677. }
  32678. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32679. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32680. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32681. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32682. }
  32683. // Draw
  32684. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32685. // Unbind
  32686. this._effectiveMaterial.unbind();
  32687. // Outline - step 2
  32688. if (this.renderOutline && savedDepthWrite) {
  32689. engine.setDepthWrite(true);
  32690. engine.setColorWrite(false);
  32691. scene.getOutlineRenderer().render(subMesh, batch);
  32692. engine.setColorWrite(true);
  32693. }
  32694. // Overlay
  32695. if (this.renderOverlay) {
  32696. var currentMode = engine.getAlphaMode();
  32697. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32698. scene.getOutlineRenderer().render(subMesh, batch, true);
  32699. engine.setAlphaMode(currentMode);
  32700. }
  32701. this.onAfterRenderObservable.notifyObservers(this);
  32702. return this;
  32703. };
  32704. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32705. if (isInstance && effectiveMaterial) {
  32706. effectiveMaterial.bindOnlyWorldMatrix(world);
  32707. }
  32708. };
  32709. /**
  32710. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32711. */
  32712. Mesh.prototype.getEmittedParticleSystems = function () {
  32713. var results = new Array();
  32714. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32715. var particleSystem = this.getScene().particleSystems[index];
  32716. if (particleSystem.emitter === this) {
  32717. results.push(particleSystem);
  32718. }
  32719. }
  32720. return results;
  32721. };
  32722. /**
  32723. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32724. */
  32725. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32726. var results = new Array();
  32727. var descendants = this.getDescendants();
  32728. descendants.push(this);
  32729. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32730. var particleSystem = this.getScene().particleSystems[index];
  32731. var emitter = particleSystem.emitter;
  32732. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32733. results.push(particleSystem);
  32734. }
  32735. }
  32736. return results;
  32737. };
  32738. /**
  32739. * Normalize matrix weights so that all vertices have a total weight set to 1
  32740. */
  32741. Mesh.prototype.cleanMatrixWeights = function () {
  32742. var epsilon = 1e-3;
  32743. var noInfluenceBoneIndex = 0.0;
  32744. if (this.skeleton) {
  32745. noInfluenceBoneIndex = this.skeleton.bones.length;
  32746. }
  32747. else {
  32748. return;
  32749. }
  32750. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32751. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32752. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32753. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32754. var influencers = this.numBoneInfluencers;
  32755. var size = matricesWeights.length;
  32756. for (var i = 0; i < size; i += 4) {
  32757. var weight = 0.0;
  32758. var firstZeroWeight = -1;
  32759. for (var j = 0; j < 4; j++) {
  32760. var w = matricesWeights[i + j];
  32761. weight += w;
  32762. if (w < epsilon && firstZeroWeight < 0) {
  32763. firstZeroWeight = j;
  32764. }
  32765. }
  32766. if (matricesWeightsExtra) {
  32767. for (var j = 0; j < 4; j++) {
  32768. var w = matricesWeightsExtra[i + j];
  32769. weight += w;
  32770. if (w < epsilon && firstZeroWeight < 0) {
  32771. firstZeroWeight = j + 4;
  32772. }
  32773. }
  32774. }
  32775. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32776. firstZeroWeight = influencers - 1;
  32777. }
  32778. if (weight > epsilon) {
  32779. var mweight = 1.0 / weight;
  32780. for (var j = 0; j < 4; j++) {
  32781. matricesWeights[i + j] *= mweight;
  32782. }
  32783. if (matricesWeightsExtra) {
  32784. for (var j = 0; j < 4; j++) {
  32785. matricesWeightsExtra[i + j] *= mweight;
  32786. }
  32787. }
  32788. }
  32789. else {
  32790. if (firstZeroWeight >= 4) {
  32791. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32792. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32793. }
  32794. else {
  32795. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32796. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32797. }
  32798. }
  32799. }
  32800. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32801. if (matricesIndicesExtra) {
  32802. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32803. }
  32804. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32805. if (matricesWeightsExtra) {
  32806. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32807. }
  32808. };
  32809. Mesh.prototype._checkDelayState = function () {
  32810. var scene = this.getScene();
  32811. if (this._geometry) {
  32812. this._geometry.load(scene);
  32813. }
  32814. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32815. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32816. this._queueLoad(scene);
  32817. }
  32818. return this;
  32819. };
  32820. Mesh.prototype._queueLoad = function (scene) {
  32821. var _this = this;
  32822. scene._addPendingData(this);
  32823. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32824. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32825. if (data instanceof ArrayBuffer) {
  32826. _this._delayLoadingFunction(data, _this);
  32827. }
  32828. else {
  32829. _this._delayLoadingFunction(JSON.parse(data), _this);
  32830. }
  32831. _this.instances.forEach(function (instance) {
  32832. instance._syncSubMeshes();
  32833. });
  32834. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32835. scene._removePendingData(_this);
  32836. }, function () { }, scene.database, getBinaryData);
  32837. return this;
  32838. };
  32839. /**
  32840. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32841. */
  32842. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32843. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32844. return false;
  32845. }
  32846. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32847. return false;
  32848. }
  32849. this._checkDelayState();
  32850. return true;
  32851. };
  32852. /**
  32853. * Sets the mesh material by the material or multiMaterial `id` property.
  32854. * The material `id` is a string identifying the material or the multiMaterial.
  32855. * This method returns the Mesh.
  32856. */
  32857. Mesh.prototype.setMaterialByID = function (id) {
  32858. var materials = this.getScene().materials;
  32859. var index;
  32860. for (index = materials.length - 1; index > -1; index--) {
  32861. if (materials[index].id === id) {
  32862. this.material = materials[index];
  32863. return this;
  32864. }
  32865. }
  32866. // Multi
  32867. var multiMaterials = this.getScene().multiMaterials;
  32868. for (index = multiMaterials.length - 1; index > -1; index--) {
  32869. if (multiMaterials[index].id === id) {
  32870. this.material = multiMaterials[index];
  32871. return this;
  32872. }
  32873. }
  32874. return this;
  32875. };
  32876. /**
  32877. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32878. */
  32879. Mesh.prototype.getAnimatables = function () {
  32880. var results = new Array();
  32881. if (this.material) {
  32882. results.push(this.material);
  32883. }
  32884. if (this.skeleton) {
  32885. results.push(this.skeleton);
  32886. }
  32887. return results;
  32888. };
  32889. /**
  32890. * Modifies the mesh geometry according to the passed transformation matrix.
  32891. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32892. * The mesh normals are modified accordingly the same transformation.
  32893. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32894. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32895. * Returns the Mesh.
  32896. */
  32897. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32898. // Position
  32899. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32900. return this;
  32901. }
  32902. var submeshes = this.subMeshes.splice(0);
  32903. this._resetPointsArrayCache();
  32904. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32905. var temp = new Array();
  32906. var index;
  32907. for (index = 0; index < data.length; index += 3) {
  32908. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32909. }
  32910. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32911. // Normals
  32912. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32913. return this;
  32914. }
  32915. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32916. temp = [];
  32917. for (index = 0; index < data.length; index += 3) {
  32918. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32919. }
  32920. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32921. // flip faces?
  32922. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32923. this.flipFaces();
  32924. }
  32925. // Restore submeshes
  32926. this.releaseSubMeshes();
  32927. this.subMeshes = submeshes;
  32928. return this;
  32929. };
  32930. /**
  32931. * Modifies the mesh geometry according to its own current World Matrix.
  32932. * The mesh World Matrix is then reset.
  32933. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32934. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32935. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32936. * Returns the Mesh.
  32937. */
  32938. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32939. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32940. this.scaling.copyFromFloats(1, 1, 1);
  32941. this.position.copyFromFloats(0, 0, 0);
  32942. this.rotation.copyFromFloats(0, 0, 0);
  32943. //only if quaternion is already set
  32944. if (this.rotationQuaternion) {
  32945. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32946. }
  32947. this._worldMatrix = BABYLON.Matrix.Identity();
  32948. return this;
  32949. };
  32950. Object.defineProperty(Mesh.prototype, "_positions", {
  32951. // Cache
  32952. get: function () {
  32953. if (this._geometry) {
  32954. return this._geometry._positions;
  32955. }
  32956. return null;
  32957. },
  32958. enumerable: true,
  32959. configurable: true
  32960. });
  32961. Mesh.prototype._resetPointsArrayCache = function () {
  32962. if (this._geometry) {
  32963. this._geometry._resetPointsArrayCache();
  32964. }
  32965. return this;
  32966. };
  32967. Mesh.prototype._generatePointsArray = function () {
  32968. if (this._geometry) {
  32969. return this._geometry._generatePointsArray();
  32970. }
  32971. return false;
  32972. };
  32973. /**
  32974. * Returns a new Mesh object generated from the current mesh properties.
  32975. * This method must not get confused with createInstance().
  32976. * The parameter `name` is a string, the name given to the new mesh.
  32977. * The optional parameter `newParent` can be any Node object (default `null`).
  32978. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32979. * 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.
  32980. */
  32981. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32982. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32983. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32984. };
  32985. /**
  32986. * Releases resources associated with this mesh.
  32987. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32988. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32989. */
  32990. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32991. var _this = this;
  32992. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32993. this.morphTargetManager = null;
  32994. if (this._geometry) {
  32995. this._geometry.releaseForMesh(this, true);
  32996. }
  32997. // Sources
  32998. var meshes = this.getScene().meshes;
  32999. meshes.forEach(function (abstractMesh) {
  33000. var mesh = abstractMesh;
  33001. if (mesh._source && mesh._source === _this) {
  33002. mesh._source = null;
  33003. }
  33004. });
  33005. this._source = null;
  33006. // Instances
  33007. if (this._instancesBuffer) {
  33008. this._instancesBuffer.dispose();
  33009. this._instancesBuffer = null;
  33010. }
  33011. while (this.instances.length) {
  33012. this.instances[0].dispose();
  33013. }
  33014. // Effect layers.
  33015. var effectLayers = this.getScene().effectLayers;
  33016. for (var i = 0; i < effectLayers.length; i++) {
  33017. var effectLayer = effectLayers[i];
  33018. if (effectLayer) {
  33019. effectLayer._disposeMesh(this);
  33020. }
  33021. }
  33022. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33023. };
  33024. /**
  33025. * Modifies the mesh geometry according to a displacement map.
  33026. * 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.
  33027. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33028. * This method returns nothing.
  33029. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  33030. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33031. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  33032. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33033. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33034. *
  33035. * Returns the Mesh.
  33036. */
  33037. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33038. var _this = this;
  33039. var scene = this.getScene();
  33040. var onload = function (img) {
  33041. // Getting height map data
  33042. var canvas = document.createElement("canvas");
  33043. var context = canvas.getContext("2d");
  33044. var heightMapWidth = img.width;
  33045. var heightMapHeight = img.height;
  33046. canvas.width = heightMapWidth;
  33047. canvas.height = heightMapHeight;
  33048. context.drawImage(img, 0, 0);
  33049. // Create VertexData from map data
  33050. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33051. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33052. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33053. //execute success callback, if set
  33054. if (onSuccess) {
  33055. onSuccess(_this);
  33056. }
  33057. };
  33058. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33059. return this;
  33060. };
  33061. /**
  33062. * Modifies the mesh geometry according to a displacementMap buffer.
  33063. * 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.
  33064. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33065. * This method returns nothing.
  33066. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33067. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33068. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33069. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33070. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33071. *
  33072. * Returns the Mesh.
  33073. */
  33074. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33075. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33076. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33077. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33078. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33079. return this;
  33080. }
  33081. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33082. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33083. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33084. var position = BABYLON.Vector3.Zero();
  33085. var normal = BABYLON.Vector3.Zero();
  33086. var uv = BABYLON.Vector2.Zero();
  33087. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33088. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33089. for (var index = 0; index < positions.length; index += 3) {
  33090. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33091. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33092. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33093. // Compute height
  33094. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33095. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33096. var pos = (u + v * heightMapWidth) * 4;
  33097. var r = buffer[pos] / 255.0;
  33098. var g = buffer[pos + 1] / 255.0;
  33099. var b = buffer[pos + 2] / 255.0;
  33100. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33101. normal.normalize();
  33102. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33103. position = position.add(normal);
  33104. position.toArray(positions, index);
  33105. }
  33106. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33107. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33108. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33109. return this;
  33110. };
  33111. /**
  33112. * Modify the mesh to get a flat shading rendering.
  33113. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33114. * This method returns the Mesh.
  33115. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33116. */
  33117. Mesh.prototype.convertToFlatShadedMesh = function () {
  33118. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33119. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33120. var kinds = this.getVerticesDataKinds();
  33121. var vbs = {};
  33122. var data = {};
  33123. var newdata = {};
  33124. var updatableNormals = false;
  33125. var kindIndex;
  33126. var kind;
  33127. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33128. kind = kinds[kindIndex];
  33129. var vertexBuffer = this.getVertexBuffer(kind);
  33130. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33131. updatableNormals = vertexBuffer.isUpdatable();
  33132. kinds.splice(kindIndex, 1);
  33133. kindIndex--;
  33134. continue;
  33135. }
  33136. vbs[kind] = vertexBuffer;
  33137. data[kind] = vbs[kind].getData();
  33138. newdata[kind] = [];
  33139. }
  33140. // Save previous submeshes
  33141. var previousSubmeshes = this.subMeshes.slice(0);
  33142. var indices = this.getIndices();
  33143. var totalIndices = this.getTotalIndices();
  33144. // Generating unique vertices per face
  33145. var index;
  33146. for (index = 0; index < totalIndices; index++) {
  33147. var vertexIndex = indices[index];
  33148. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33149. kind = kinds[kindIndex];
  33150. var stride = vbs[kind].getStrideSize();
  33151. for (var offset = 0; offset < stride; offset++) {
  33152. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33153. }
  33154. }
  33155. }
  33156. // Updating faces & normal
  33157. var normals = [];
  33158. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33159. for (index = 0; index < totalIndices; index += 3) {
  33160. indices[index] = index;
  33161. indices[index + 1] = index + 1;
  33162. indices[index + 2] = index + 2;
  33163. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33164. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33165. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33166. var p1p2 = p1.subtract(p2);
  33167. var p3p2 = p3.subtract(p2);
  33168. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33169. // Store same normals for every vertex
  33170. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33171. normals.push(normal.x);
  33172. normals.push(normal.y);
  33173. normals.push(normal.z);
  33174. }
  33175. }
  33176. this.setIndices(indices);
  33177. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33178. // Updating vertex buffers
  33179. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33180. kind = kinds[kindIndex];
  33181. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33182. }
  33183. // Updating submeshes
  33184. this.releaseSubMeshes();
  33185. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33186. var previousOne = previousSubmeshes[submeshIndex];
  33187. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33188. }
  33189. this.synchronizeInstances();
  33190. return this;
  33191. };
  33192. /**
  33193. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33194. * In other words, more vertices, no more indices and a single bigger VBO.
  33195. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33196. * Returns the Mesh.
  33197. */
  33198. Mesh.prototype.convertToUnIndexedMesh = function () {
  33199. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33200. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33201. var kinds = this.getVerticesDataKinds();
  33202. var vbs = {};
  33203. var data = {};
  33204. var newdata = {};
  33205. var kindIndex;
  33206. var kind;
  33207. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33208. kind = kinds[kindIndex];
  33209. var vertexBuffer = this.getVertexBuffer(kind);
  33210. vbs[kind] = vertexBuffer;
  33211. data[kind] = vbs[kind].getData();
  33212. newdata[kind] = [];
  33213. }
  33214. // Save previous submeshes
  33215. var previousSubmeshes = this.subMeshes.slice(0);
  33216. var indices = this.getIndices();
  33217. var totalIndices = this.getTotalIndices();
  33218. // Generating unique vertices per face
  33219. var index;
  33220. for (index = 0; index < totalIndices; index++) {
  33221. var vertexIndex = indices[index];
  33222. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33223. kind = kinds[kindIndex];
  33224. var stride = vbs[kind].getStrideSize();
  33225. for (var offset = 0; offset < stride; offset++) {
  33226. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33227. }
  33228. }
  33229. }
  33230. // Updating indices
  33231. for (index = 0; index < totalIndices; index += 3) {
  33232. indices[index] = index;
  33233. indices[index + 1] = index + 1;
  33234. indices[index + 2] = index + 2;
  33235. }
  33236. this.setIndices(indices);
  33237. // Updating vertex buffers
  33238. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33239. kind = kinds[kindIndex];
  33240. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33241. }
  33242. // Updating submeshes
  33243. this.releaseSubMeshes();
  33244. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33245. var previousOne = previousSubmeshes[submeshIndex];
  33246. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33247. }
  33248. this._unIndexed = true;
  33249. this.synchronizeInstances();
  33250. return this;
  33251. };
  33252. /**
  33253. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33254. * This method returns the Mesh.
  33255. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33256. */
  33257. Mesh.prototype.flipFaces = function (flipNormals) {
  33258. if (flipNormals === void 0) { flipNormals = false; }
  33259. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33260. var i;
  33261. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33262. for (i = 0; i < vertex_data.normals.length; i++) {
  33263. vertex_data.normals[i] *= -1;
  33264. }
  33265. }
  33266. if (vertex_data.indices) {
  33267. var temp;
  33268. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33269. // reassign indices
  33270. temp = vertex_data.indices[i + 1];
  33271. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33272. vertex_data.indices[i + 2] = temp;
  33273. }
  33274. }
  33275. vertex_data.applyToMesh(this);
  33276. return this;
  33277. };
  33278. // Instances
  33279. /**
  33280. * Creates a new InstancedMesh object from the mesh model.
  33281. * An instance shares the same properties and the same material than its model.
  33282. * Only these properties of each instance can then be set individually :
  33283. * - position
  33284. * - rotation
  33285. * - rotationQuaternion
  33286. * - setPivotMatrix
  33287. * - scaling
  33288. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33289. * Warning : this method is not supported for Line mesh and LineSystem
  33290. */
  33291. Mesh.prototype.createInstance = function (name) {
  33292. return new BABYLON.InstancedMesh(name, this);
  33293. };
  33294. /**
  33295. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33296. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33297. * This method returns the Mesh.
  33298. */
  33299. Mesh.prototype.synchronizeInstances = function () {
  33300. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33301. var instance = this.instances[instanceIndex];
  33302. instance._syncSubMeshes();
  33303. }
  33304. return this;
  33305. };
  33306. /**
  33307. * Simplify the mesh according to the given array of settings.
  33308. * Function will return immediately and will simplify async. It returns the Mesh.
  33309. * @param settings a collection of simplification settings.
  33310. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33311. * @param type the type of simplification to run.
  33312. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33313. */
  33314. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33315. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33316. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33317. this.getScene().simplificationQueue.addTask({
  33318. settings: settings,
  33319. parallelProcessing: parallelProcessing,
  33320. mesh: this,
  33321. simplificationType: simplificationType,
  33322. successCallback: successCallback
  33323. });
  33324. return this;
  33325. };
  33326. /**
  33327. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33328. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33329. * This should be used together with the simplification to avoid disappearing triangles.
  33330. * Returns the Mesh.
  33331. * @param successCallback an optional success callback to be called after the optimization finished.
  33332. */
  33333. Mesh.prototype.optimizeIndices = function (successCallback) {
  33334. var _this = this;
  33335. var indices = this.getIndices();
  33336. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33337. if (!positions || !indices) {
  33338. return this;
  33339. }
  33340. var vectorPositions = new Array();
  33341. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33342. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33343. }
  33344. var dupes = new Array();
  33345. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33346. var realPos = vectorPositions.length - 1 - iteration;
  33347. var testedPosition = vectorPositions[realPos];
  33348. for (var j = 0; j < realPos; ++j) {
  33349. var againstPosition = vectorPositions[j];
  33350. if (testedPosition.equals(againstPosition)) {
  33351. dupes[realPos] = j;
  33352. break;
  33353. }
  33354. }
  33355. }, function () {
  33356. for (var i = 0; i < indices.length; ++i) {
  33357. indices[i] = dupes[indices[i]] || indices[i];
  33358. }
  33359. //indices are now reordered
  33360. var originalSubMeshes = _this.subMeshes.slice(0);
  33361. _this.setIndices(indices);
  33362. _this.subMeshes = originalSubMeshes;
  33363. if (successCallback) {
  33364. successCallback(_this);
  33365. }
  33366. });
  33367. return this;
  33368. };
  33369. Mesh.prototype.serialize = function (serializationObject) {
  33370. serializationObject.name = this.name;
  33371. serializationObject.id = this.id;
  33372. serializationObject.type = this.getClassName();
  33373. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33374. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33375. }
  33376. serializationObject.position = this.position.asArray();
  33377. if (this.rotationQuaternion) {
  33378. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33379. }
  33380. else if (this.rotation) {
  33381. serializationObject.rotation = this.rotation.asArray();
  33382. }
  33383. serializationObject.scaling = this.scaling.asArray();
  33384. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33385. serializationObject.isEnabled = this.isEnabled(false);
  33386. serializationObject.isVisible = this.isVisible;
  33387. serializationObject.infiniteDistance = this.infiniteDistance;
  33388. serializationObject.pickable = this.isPickable;
  33389. serializationObject.receiveShadows = this.receiveShadows;
  33390. serializationObject.billboardMode = this.billboardMode;
  33391. serializationObject.visibility = this.visibility;
  33392. serializationObject.checkCollisions = this.checkCollisions;
  33393. serializationObject.isBlocker = this.isBlocker;
  33394. // Parent
  33395. if (this.parent) {
  33396. serializationObject.parentId = this.parent.id;
  33397. }
  33398. // Geometry
  33399. serializationObject.isUnIndexed = this.isUnIndexed;
  33400. var geometry = this._geometry;
  33401. if (geometry) {
  33402. var geometryId = geometry.id;
  33403. serializationObject.geometryId = geometryId;
  33404. // SubMeshes
  33405. serializationObject.subMeshes = [];
  33406. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33407. var subMesh = this.subMeshes[subIndex];
  33408. serializationObject.subMeshes.push({
  33409. materialIndex: subMesh.materialIndex,
  33410. verticesStart: subMesh.verticesStart,
  33411. verticesCount: subMesh.verticesCount,
  33412. indexStart: subMesh.indexStart,
  33413. indexCount: subMesh.indexCount
  33414. });
  33415. }
  33416. }
  33417. // Material
  33418. if (this.material) {
  33419. serializationObject.materialId = this.material.id;
  33420. }
  33421. else {
  33422. this.material = null;
  33423. }
  33424. // Morph targets
  33425. if (this.morphTargetManager) {
  33426. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33427. }
  33428. // Skeleton
  33429. if (this.skeleton) {
  33430. serializationObject.skeletonId = this.skeleton.id;
  33431. }
  33432. // Physics
  33433. //TODO implement correct serialization for physics impostors.
  33434. var impostor = this.getPhysicsImpostor();
  33435. if (impostor) {
  33436. serializationObject.physicsMass = impostor.getParam("mass");
  33437. serializationObject.physicsFriction = impostor.getParam("friction");
  33438. serializationObject.physicsRestitution = impostor.getParam("mass");
  33439. serializationObject.physicsImpostor = impostor.type;
  33440. }
  33441. // Metadata
  33442. if (this.metadata) {
  33443. serializationObject.metadata = this.metadata;
  33444. }
  33445. // Instances
  33446. serializationObject.instances = [];
  33447. for (var index = 0; index < this.instances.length; index++) {
  33448. var instance = this.instances[index];
  33449. var serializationInstance = {
  33450. name: instance.name,
  33451. id: instance.id,
  33452. position: instance.position.asArray(),
  33453. scaling: instance.scaling.asArray()
  33454. };
  33455. if (instance.rotationQuaternion) {
  33456. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33457. }
  33458. else if (instance.rotation) {
  33459. serializationInstance.rotation = instance.rotation.asArray();
  33460. }
  33461. serializationObject.instances.push(serializationInstance);
  33462. // Animations
  33463. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33464. serializationInstance.ranges = instance.serializeAnimationRanges();
  33465. }
  33466. //
  33467. // Animations
  33468. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33469. serializationObject.ranges = this.serializeAnimationRanges();
  33470. // Layer mask
  33471. serializationObject.layerMask = this.layerMask;
  33472. // Alpha
  33473. serializationObject.alphaIndex = this.alphaIndex;
  33474. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33475. // Overlay
  33476. serializationObject.overlayAlpha = this.overlayAlpha;
  33477. serializationObject.overlayColor = this.overlayColor.asArray();
  33478. serializationObject.renderOverlay = this.renderOverlay;
  33479. // Fog
  33480. serializationObject.applyFog = this.applyFog;
  33481. // Action Manager
  33482. if (this.actionManager) {
  33483. serializationObject.actions = this.actionManager.serialize(this.name);
  33484. }
  33485. };
  33486. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33487. if (!this.geometry) {
  33488. return;
  33489. }
  33490. this._markSubMeshesAsAttributesDirty();
  33491. var morphTargetManager = this._morphTargetManager;
  33492. if (morphTargetManager && morphTargetManager.vertexCount) {
  33493. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33494. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33495. this.morphTargetManager = null;
  33496. return;
  33497. }
  33498. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33499. var morphTarget = morphTargetManager.getActiveTarget(index);
  33500. var positions = morphTarget.getPositions();
  33501. if (!positions) {
  33502. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33503. return;
  33504. }
  33505. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33506. var normals = morphTarget.getNormals();
  33507. if (normals) {
  33508. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33509. }
  33510. var tangents = morphTarget.getTangents();
  33511. if (tangents) {
  33512. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33513. }
  33514. }
  33515. }
  33516. else {
  33517. var index = 0;
  33518. // Positions
  33519. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33520. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33521. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33522. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33523. }
  33524. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33525. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33526. }
  33527. index++;
  33528. }
  33529. }
  33530. };
  33531. // Statics
  33532. /**
  33533. * Returns a new Mesh object parsed from the source provided.
  33534. * The parameter `parsedMesh` is the source.
  33535. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33536. */
  33537. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33538. var mesh;
  33539. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33540. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33541. }
  33542. else {
  33543. mesh = new Mesh(parsedMesh.name, scene);
  33544. }
  33545. mesh.id = parsedMesh.id;
  33546. if (BABYLON.Tags) {
  33547. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33548. }
  33549. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33550. if (parsedMesh.metadata !== undefined) {
  33551. mesh.metadata = parsedMesh.metadata;
  33552. }
  33553. if (parsedMesh.rotationQuaternion) {
  33554. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33555. }
  33556. else if (parsedMesh.rotation) {
  33557. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33558. }
  33559. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33560. if (parsedMesh.localMatrix) {
  33561. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33562. }
  33563. else if (parsedMesh.pivotMatrix) {
  33564. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33565. }
  33566. mesh.setEnabled(parsedMesh.isEnabled);
  33567. mesh.isVisible = parsedMesh.isVisible;
  33568. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33569. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33570. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33571. if (parsedMesh.applyFog !== undefined) {
  33572. mesh.applyFog = parsedMesh.applyFog;
  33573. }
  33574. if (parsedMesh.pickable !== undefined) {
  33575. mesh.isPickable = parsedMesh.pickable;
  33576. }
  33577. if (parsedMesh.alphaIndex !== undefined) {
  33578. mesh.alphaIndex = parsedMesh.alphaIndex;
  33579. }
  33580. mesh.receiveShadows = parsedMesh.receiveShadows;
  33581. mesh.billboardMode = parsedMesh.billboardMode;
  33582. if (parsedMesh.visibility !== undefined) {
  33583. mesh.visibility = parsedMesh.visibility;
  33584. }
  33585. mesh.checkCollisions = parsedMesh.checkCollisions;
  33586. if (parsedMesh.isBlocker !== undefined) {
  33587. mesh.isBlocker = parsedMesh.isBlocker;
  33588. }
  33589. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33590. // freezeWorldMatrix
  33591. if (parsedMesh.freezeWorldMatrix) {
  33592. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33593. }
  33594. // Parent
  33595. if (parsedMesh.parentId) {
  33596. mesh._waitingParentId = parsedMesh.parentId;
  33597. }
  33598. // Actions
  33599. if (parsedMesh.actions !== undefined) {
  33600. mesh._waitingActions = parsedMesh.actions;
  33601. }
  33602. // Overlay
  33603. if (parsedMesh.overlayAlpha !== undefined) {
  33604. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33605. }
  33606. if (parsedMesh.overlayColor !== undefined) {
  33607. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33608. }
  33609. if (parsedMesh.renderOverlay !== undefined) {
  33610. mesh.renderOverlay = parsedMesh.renderOverlay;
  33611. }
  33612. // Geometry
  33613. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33614. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33615. if (parsedMesh.delayLoadingFile) {
  33616. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33617. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33618. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33619. if (parsedMesh._binaryInfo) {
  33620. mesh._binaryInfo = parsedMesh._binaryInfo;
  33621. }
  33622. mesh._delayInfo = [];
  33623. if (parsedMesh.hasUVs) {
  33624. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33625. }
  33626. if (parsedMesh.hasUVs2) {
  33627. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33628. }
  33629. if (parsedMesh.hasUVs3) {
  33630. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33631. }
  33632. if (parsedMesh.hasUVs4) {
  33633. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33634. }
  33635. if (parsedMesh.hasUVs5) {
  33636. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33637. }
  33638. if (parsedMesh.hasUVs6) {
  33639. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33640. }
  33641. if (parsedMesh.hasColors) {
  33642. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33643. }
  33644. if (parsedMesh.hasMatricesIndices) {
  33645. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33646. }
  33647. if (parsedMesh.hasMatricesWeights) {
  33648. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33649. }
  33650. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33651. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33652. mesh._checkDelayState();
  33653. }
  33654. }
  33655. else {
  33656. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33657. }
  33658. // Material
  33659. if (parsedMesh.materialId) {
  33660. mesh.setMaterialByID(parsedMesh.materialId);
  33661. }
  33662. else {
  33663. mesh.material = null;
  33664. }
  33665. // Morph targets
  33666. if (parsedMesh.morphTargetManagerId > -1) {
  33667. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33668. }
  33669. // Skeleton
  33670. if (parsedMesh.skeletonId > -1) {
  33671. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33672. if (parsedMesh.numBoneInfluencers) {
  33673. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33674. }
  33675. }
  33676. // Animations
  33677. if (parsedMesh.animations) {
  33678. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33679. var parsedAnimation = parsedMesh.animations[animationIndex];
  33680. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33681. }
  33682. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33683. }
  33684. if (parsedMesh.autoAnimate) {
  33685. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33686. }
  33687. // Layer Mask
  33688. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33689. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33690. }
  33691. else {
  33692. mesh.layerMask = 0x0FFFFFFF;
  33693. }
  33694. // Physics
  33695. if (parsedMesh.physicsImpostor) {
  33696. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33697. mass: parsedMesh.physicsMass,
  33698. friction: parsedMesh.physicsFriction,
  33699. restitution: parsedMesh.physicsRestitution
  33700. }, scene);
  33701. }
  33702. // Instances
  33703. if (parsedMesh.instances) {
  33704. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33705. var parsedInstance = parsedMesh.instances[index];
  33706. var instance = mesh.createInstance(parsedInstance.name);
  33707. if (parsedInstance.id) {
  33708. instance.id = parsedInstance.id;
  33709. }
  33710. if (BABYLON.Tags) {
  33711. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33712. }
  33713. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33714. if (parsedInstance.parentId) {
  33715. instance._waitingParentId = parsedInstance.parentId;
  33716. }
  33717. if (parsedInstance.rotationQuaternion) {
  33718. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33719. }
  33720. else if (parsedInstance.rotation) {
  33721. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33722. }
  33723. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33724. instance.checkCollisions = mesh.checkCollisions;
  33725. if (parsedMesh.animations) {
  33726. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33727. parsedAnimation = parsedMesh.animations[animationIndex];
  33728. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33729. }
  33730. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33731. if (parsedMesh.autoAnimate) {
  33732. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33733. }
  33734. }
  33735. }
  33736. }
  33737. return mesh;
  33738. };
  33739. /**
  33740. * Creates a ribbon mesh.
  33741. * Please consider using the same method from the MeshBuilder class instead.
  33742. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33743. *
  33744. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33745. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33746. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33747. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33748. * 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.
  33749. * 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.
  33750. * 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
  33751. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33752. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33753. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33754. */
  33755. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33756. if (closeArray === void 0) { closeArray = false; }
  33757. if (updatable === void 0) { updatable = false; }
  33758. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33759. pathArray: pathArray,
  33760. closeArray: closeArray,
  33761. closePath: closePath,
  33762. offset: offset,
  33763. updatable: updatable,
  33764. sideOrientation: sideOrientation,
  33765. instance: instance
  33766. }, scene);
  33767. };
  33768. /**
  33769. * Creates a plane polygonal mesh. By default, this is a disc.
  33770. * Please consider using the same method from the MeshBuilder class instead.
  33771. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33772. * 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.
  33773. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33774. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33776. */
  33777. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33778. if (scene === void 0) { scene = null; }
  33779. var options = {
  33780. radius: radius,
  33781. tessellation: tessellation,
  33782. sideOrientation: sideOrientation,
  33783. updatable: updatable
  33784. };
  33785. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33786. };
  33787. /**
  33788. * Creates a box mesh.
  33789. * Please consider using the same method from the MeshBuilder class instead.
  33790. * The parameter `size` sets the size (float) of each box side (default 1).
  33791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33792. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33794. */
  33795. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33796. if (scene === void 0) { scene = null; }
  33797. var options = {
  33798. size: size,
  33799. sideOrientation: sideOrientation,
  33800. updatable: updatable
  33801. };
  33802. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33803. };
  33804. /**
  33805. * Creates a sphere mesh.
  33806. * Please consider using the same method from the MeshBuilder class instead.
  33807. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33808. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33809. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33810. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33811. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33812. */
  33813. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33814. var options = {
  33815. segments: segments,
  33816. diameterX: diameter,
  33817. diameterY: diameter,
  33818. diameterZ: diameter,
  33819. sideOrientation: sideOrientation,
  33820. updatable: updatable
  33821. };
  33822. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33823. };
  33824. /**
  33825. * Creates a cylinder or a cone mesh.
  33826. * Please consider using the same method from the MeshBuilder class instead.
  33827. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33828. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33829. * 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.
  33830. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33831. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33832. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33833. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33835. */
  33836. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33837. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33838. if (scene !== undefined) {
  33839. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33840. updatable = scene;
  33841. }
  33842. scene = subdivisions;
  33843. subdivisions = 1;
  33844. }
  33845. var options = {
  33846. height: height,
  33847. diameterTop: diameterTop,
  33848. diameterBottom: diameterBottom,
  33849. tessellation: tessellation,
  33850. subdivisions: subdivisions,
  33851. sideOrientation: sideOrientation,
  33852. updatable: updatable
  33853. };
  33854. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33855. };
  33856. // Torus (Code from SharpDX.org)
  33857. /**
  33858. * Creates a torus mesh.
  33859. * Please consider using the same method from the MeshBuilder class instead.
  33860. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33861. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33862. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33863. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33864. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  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.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33868. var options = {
  33869. diameter: diameter,
  33870. thickness: thickness,
  33871. tessellation: tessellation,
  33872. sideOrientation: sideOrientation,
  33873. updatable: updatable
  33874. };
  33875. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33876. };
  33877. /**
  33878. * Creates a torus knot mesh.
  33879. * Please consider using the same method from the MeshBuilder class instead.
  33880. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33881. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33882. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33883. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33884. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33885. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33887. */
  33888. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33889. var options = {
  33890. radius: radius,
  33891. tube: tube,
  33892. radialSegments: radialSegments,
  33893. tubularSegments: tubularSegments,
  33894. p: p,
  33895. q: q,
  33896. sideOrientation: sideOrientation,
  33897. updatable: updatable
  33898. };
  33899. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33900. };
  33901. /**
  33902. * Creates a line mesh.
  33903. * Please consider using the same method from the MeshBuilder class instead.
  33904. * 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.
  33905. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33906. * The parameter `points` is an array successive Vector3.
  33907. * 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
  33908. * When updating an instance, remember that only point positions can change, not the number of points.
  33909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33910. */
  33911. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33912. if (scene === void 0) { scene = null; }
  33913. if (updatable === void 0) { updatable = false; }
  33914. if (instance === void 0) { instance = null; }
  33915. var options = {
  33916. points: points,
  33917. updatable: updatable,
  33918. instance: instance
  33919. };
  33920. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33921. };
  33922. /**
  33923. * Creates a dashed line mesh.
  33924. * Please consider using the same method from the MeshBuilder class instead.
  33925. * 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.
  33926. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33927. * The parameter `points` is an array successive Vector3.
  33928. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33929. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33930. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33931. * 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
  33932. * When updating an instance, remember that only point positions can change, not the number of points.
  33933. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33934. */
  33935. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33936. if (scene === void 0) { scene = null; }
  33937. var options = {
  33938. points: points,
  33939. dashSize: dashSize,
  33940. gapSize: gapSize,
  33941. dashNb: dashNb,
  33942. updatable: updatable,
  33943. instance: instance
  33944. };
  33945. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33946. };
  33947. /**
  33948. * Creates a polygon mesh.
  33949. * Please consider using the same method from the MeshBuilder class instead.
  33950. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33951. * 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.
  33952. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33953. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33954. * Remember you can only change the shape positions, not their number when updating a polygon.
  33955. */
  33956. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33957. var options = {
  33958. shape: shape,
  33959. holes: holes,
  33960. updatable: updatable,
  33961. sideOrientation: sideOrientation
  33962. };
  33963. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33964. };
  33965. /**
  33966. * Creates an extruded polygon mesh, with depth in the Y direction.
  33967. * Please consider using the same method from the MeshBuilder class instead.
  33968. */
  33969. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33970. var options = {
  33971. shape: shape,
  33972. holes: holes,
  33973. depth: depth,
  33974. updatable: updatable,
  33975. sideOrientation: sideOrientation
  33976. };
  33977. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33978. };
  33979. /**
  33980. * Creates an extruded shape mesh.
  33981. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33982. * Please consider using the same method from the MeshBuilder class instead.
  33983. *
  33984. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33985. * 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
  33986. * extruded along the Z axis.
  33987. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33988. * 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.
  33989. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33990. * 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
  33991. * 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
  33992. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33993. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33994. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33996. */
  33997. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33998. if (scene === void 0) { scene = null; }
  33999. var options = {
  34000. shape: shape,
  34001. path: path,
  34002. scale: scale,
  34003. rotation: rotation,
  34004. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34005. sideOrientation: sideOrientation,
  34006. instance: instance,
  34007. updatable: updatable
  34008. };
  34009. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34010. };
  34011. /**
  34012. * Creates an custom extruded shape mesh.
  34013. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  34014. * Please consider using the same method from the MeshBuilder class instead.
  34015. *
  34016. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34017. * 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
  34018. * extruded along the Z axis.
  34019. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34020. * 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
  34021. * and the distance of this point from the begining of the path :
  34022. * ```javascript
  34023. * var rotationFunction = function(i, distance) {
  34024. * // do things
  34025. * return rotationValue; }
  34026. * ```
  34027. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  34028. * 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
  34029. * and the distance of this point from the begining of the path :
  34030. * ```javascript
  34031. * var scaleFunction = function(i, distance) {
  34032. * // do things
  34033. * return scaleValue;}
  34034. * ```
  34035. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34036. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34037. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34038. * 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
  34039. * 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
  34040. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34041. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34042. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34043. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34044. */
  34045. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34046. var options = {
  34047. shape: shape,
  34048. path: path,
  34049. scaleFunction: scaleFunction,
  34050. rotationFunction: rotationFunction,
  34051. ribbonCloseArray: ribbonCloseArray,
  34052. ribbonClosePath: ribbonClosePath,
  34053. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34054. sideOrientation: sideOrientation,
  34055. instance: instance,
  34056. updatable: updatable
  34057. };
  34058. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34059. };
  34060. /**
  34061. * Creates lathe mesh.
  34062. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34063. * Please consider using the same method from the MeshBuilder class instead.
  34064. * 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
  34065. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34066. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34067. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34068. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34069. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34070. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34071. */
  34072. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34073. var options = {
  34074. shape: shape,
  34075. radius: radius,
  34076. tessellation: tessellation,
  34077. sideOrientation: sideOrientation,
  34078. updatable: updatable
  34079. };
  34080. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34081. };
  34082. /**
  34083. * Creates a plane mesh.
  34084. * Please consider using the same method from the MeshBuilder class instead.
  34085. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34086. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34087. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34089. */
  34090. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34091. var options = {
  34092. size: size,
  34093. width: size,
  34094. height: size,
  34095. sideOrientation: sideOrientation,
  34096. updatable: updatable
  34097. };
  34098. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34099. };
  34100. /**
  34101. * Creates a ground mesh.
  34102. * Please consider using the same method from the MeshBuilder class instead.
  34103. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34104. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34105. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34106. */
  34107. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34108. var options = {
  34109. width: width,
  34110. height: height,
  34111. subdivisions: subdivisions,
  34112. updatable: updatable
  34113. };
  34114. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34115. };
  34116. /**
  34117. * Creates a tiled ground mesh.
  34118. * Please consider using the same method from the MeshBuilder class instead.
  34119. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34120. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34121. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34122. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34123. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34124. * numbers of subdivisions on the ground width and height of each tile.
  34125. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34126. */
  34127. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34128. var options = {
  34129. xmin: xmin,
  34130. zmin: zmin,
  34131. xmax: xmax,
  34132. zmax: zmax,
  34133. subdivisions: subdivisions,
  34134. precision: precision,
  34135. updatable: updatable
  34136. };
  34137. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34138. };
  34139. /**
  34140. * Creates a ground mesh from a height map.
  34141. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34142. * Please consider using the same method from the MeshBuilder class instead.
  34143. * The parameter `url` sets the URL of the height map image resource.
  34144. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34145. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34146. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34147. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34148. * 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).
  34149. * This function is passed the newly built mesh :
  34150. * ```javascript
  34151. * function(mesh) { // do things
  34152. * return; }
  34153. * ```
  34154. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34155. */
  34156. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34157. var options = {
  34158. width: width,
  34159. height: height,
  34160. subdivisions: subdivisions,
  34161. minHeight: minHeight,
  34162. maxHeight: maxHeight,
  34163. updatable: updatable,
  34164. onReady: onReady
  34165. };
  34166. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34167. };
  34168. /**
  34169. * Creates a tube mesh.
  34170. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  34171. * Please consider using the same method from the MeshBuilder class instead.
  34172. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34173. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34174. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34175. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34176. * 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.
  34177. * It must return a radius value (positive float) :
  34178. * ```javascript
  34179. * var radiusFunction = function(i, distance) {
  34180. * // do things
  34181. * return radius; }
  34182. * ```
  34183. * 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
  34184. * 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
  34185. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34186. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34188. */
  34189. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34190. var options = {
  34191. path: path,
  34192. radius: radius,
  34193. tessellation: tessellation,
  34194. radiusFunction: radiusFunction,
  34195. arc: 1,
  34196. cap: cap,
  34197. updatable: updatable,
  34198. sideOrientation: sideOrientation,
  34199. instance: instance
  34200. };
  34201. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34202. };
  34203. /**
  34204. * Creates a polyhedron mesh.
  34205. * Please consider using the same method from the MeshBuilder class instead.
  34206. * 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
  34207. * to choose the wanted type.
  34208. * The parameter `size` (positive float, default 1) sets the polygon size.
  34209. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34210. * 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`.
  34211. * 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
  34212. * 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)`).
  34213. * 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
  34214. * 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.
  34215. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34216. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34218. */
  34219. Mesh.CreatePolyhedron = function (name, options, scene) {
  34220. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34221. };
  34222. /**
  34223. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34224. * Please consider using the same method from the MeshBuilder class instead.
  34225. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34226. * 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`).
  34227. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34228. * 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.
  34229. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34230. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34232. */
  34233. Mesh.CreateIcoSphere = function (name, options, scene) {
  34234. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34235. };
  34236. /**
  34237. * Creates a decal mesh.
  34238. * Please consider using the same method from the MeshBuilder class instead.
  34239. * 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.
  34240. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34241. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34242. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34243. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34244. */
  34245. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34246. var options = {
  34247. position: position,
  34248. normal: normal,
  34249. size: size,
  34250. angle: angle
  34251. };
  34252. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34253. };
  34254. // Skeletons
  34255. /**
  34256. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34257. */
  34258. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34259. if (!this._sourcePositions) {
  34260. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34261. if (!source) {
  34262. return this._sourcePositions;
  34263. }
  34264. this._sourcePositions = new Float32Array(source);
  34265. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34266. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34267. }
  34268. }
  34269. return this._sourcePositions;
  34270. };
  34271. /**
  34272. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34273. */
  34274. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34275. if (!this._sourceNormals) {
  34276. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34277. if (!source) {
  34278. return this._sourceNormals;
  34279. }
  34280. this._sourceNormals = new Float32Array(source);
  34281. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34282. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34283. }
  34284. }
  34285. return this._sourceNormals;
  34286. };
  34287. /**
  34288. * Updates the vertex buffer by applying transformation from the bones.
  34289. * Returns the Mesh.
  34290. *
  34291. * @param {skeleton} skeleton to apply
  34292. */
  34293. Mesh.prototype.applySkeleton = function (skeleton) {
  34294. if (!this.geometry) {
  34295. return this;
  34296. }
  34297. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34298. return this;
  34299. }
  34300. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34301. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34302. return this;
  34303. }
  34304. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34305. return this;
  34306. }
  34307. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34308. return this;
  34309. }
  34310. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34311. return this;
  34312. }
  34313. if (!this._sourcePositions) {
  34314. var submeshes = this.subMeshes.slice();
  34315. this.setPositionsForCPUSkinning();
  34316. this.subMeshes = submeshes;
  34317. }
  34318. if (!this._sourceNormals) {
  34319. this.setNormalsForCPUSkinning();
  34320. }
  34321. // positionsData checks for not being Float32Array will only pass at most once
  34322. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34323. if (!positionsData) {
  34324. return this;
  34325. }
  34326. if (!(positionsData instanceof Float32Array)) {
  34327. positionsData = new Float32Array(positionsData);
  34328. }
  34329. // normalsData checks for not being Float32Array will only pass at most once
  34330. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34331. if (!normalsData) {
  34332. return this;
  34333. }
  34334. if (!(normalsData instanceof Float32Array)) {
  34335. normalsData = new Float32Array(normalsData);
  34336. }
  34337. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34338. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34339. if (!matricesWeightsData || !matricesIndicesData) {
  34340. return this;
  34341. }
  34342. var needExtras = this.numBoneInfluencers > 4;
  34343. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34344. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34345. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34346. var tempVector3 = BABYLON.Vector3.Zero();
  34347. var finalMatrix = new BABYLON.Matrix();
  34348. var tempMatrix = new BABYLON.Matrix();
  34349. var matWeightIdx = 0;
  34350. var inf;
  34351. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34352. var weight;
  34353. for (inf = 0; inf < 4; inf++) {
  34354. weight = matricesWeightsData[matWeightIdx + inf];
  34355. if (weight > 0) {
  34356. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34357. finalMatrix.addToSelf(tempMatrix);
  34358. }
  34359. else
  34360. break;
  34361. }
  34362. if (needExtras) {
  34363. for (inf = 0; inf < 4; inf++) {
  34364. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34365. if (weight > 0) {
  34366. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34367. finalMatrix.addToSelf(tempMatrix);
  34368. }
  34369. else
  34370. break;
  34371. }
  34372. }
  34373. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34374. tempVector3.toArray(positionsData, index);
  34375. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34376. tempVector3.toArray(normalsData, index);
  34377. finalMatrix.reset();
  34378. }
  34379. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34380. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34381. return this;
  34382. };
  34383. // Tools
  34384. /**
  34385. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34386. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34387. */
  34388. Mesh.MinMax = function (meshes) {
  34389. var minVector = null;
  34390. var maxVector = null;
  34391. meshes.forEach(function (mesh, index, array) {
  34392. var boundingInfo = mesh.getBoundingInfo();
  34393. var boundingBox = boundingInfo.boundingBox;
  34394. if (!minVector || !maxVector) {
  34395. minVector = boundingBox.minimumWorld;
  34396. maxVector = boundingBox.maximumWorld;
  34397. }
  34398. else {
  34399. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34400. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34401. }
  34402. });
  34403. if (!minVector || !maxVector) {
  34404. return {
  34405. min: BABYLON.Vector3.Zero(),
  34406. max: BABYLON.Vector3.Zero()
  34407. };
  34408. }
  34409. return {
  34410. min: minVector,
  34411. max: maxVector
  34412. };
  34413. };
  34414. /**
  34415. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34416. */
  34417. Mesh.Center = function (meshesOrMinMaxVector) {
  34418. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34419. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34420. };
  34421. /**
  34422. * Merge the array of meshes into a single mesh for performance reasons.
  34423. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34424. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34425. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34426. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34427. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34428. */
  34429. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34430. if (disposeSource === void 0) { disposeSource = true; }
  34431. var index;
  34432. if (!allow32BitsIndices) {
  34433. var totalVertices = 0;
  34434. // Counting vertices
  34435. for (index = 0; index < meshes.length; index++) {
  34436. if (meshes[index]) {
  34437. totalVertices += meshes[index].getTotalVertices();
  34438. if (totalVertices > 65536) {
  34439. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34440. return null;
  34441. }
  34442. }
  34443. }
  34444. }
  34445. // Merge
  34446. var vertexData = null;
  34447. var otherVertexData;
  34448. var indiceArray = new Array();
  34449. var source = null;
  34450. for (index = 0; index < meshes.length; index++) {
  34451. if (meshes[index]) {
  34452. meshes[index].computeWorldMatrix(true);
  34453. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34454. otherVertexData.transform(meshes[index].getWorldMatrix());
  34455. if (vertexData) {
  34456. vertexData.merge(otherVertexData);
  34457. }
  34458. else {
  34459. vertexData = otherVertexData;
  34460. source = meshes[index];
  34461. }
  34462. if (subdivideWithSubMeshes) {
  34463. indiceArray.push(meshes[index].getTotalIndices());
  34464. }
  34465. }
  34466. }
  34467. source = source;
  34468. if (!meshSubclass) {
  34469. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34470. }
  34471. vertexData.applyToMesh(meshSubclass);
  34472. // Setting properties
  34473. meshSubclass.material = source.material;
  34474. meshSubclass.checkCollisions = source.checkCollisions;
  34475. // Cleaning
  34476. if (disposeSource) {
  34477. for (index = 0; index < meshes.length; index++) {
  34478. if (meshes[index]) {
  34479. meshes[index].dispose();
  34480. }
  34481. }
  34482. }
  34483. // Subdivide
  34484. if (subdivideWithSubMeshes) {
  34485. //-- removal of global submesh
  34486. meshSubclass.releaseSubMeshes();
  34487. index = 0;
  34488. var offset = 0;
  34489. //-- apply subdivision according to index table
  34490. while (index < indiceArray.length) {
  34491. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34492. offset += indiceArray[index];
  34493. index++;
  34494. }
  34495. }
  34496. return meshSubclass;
  34497. };
  34498. // Consts
  34499. Mesh._FRONTSIDE = 0;
  34500. Mesh._BACKSIDE = 1;
  34501. Mesh._DOUBLESIDE = 2;
  34502. Mesh._DEFAULTSIDE = 0;
  34503. Mesh._NO_CAP = 0;
  34504. Mesh._CAP_START = 1;
  34505. Mesh._CAP_END = 2;
  34506. Mesh._CAP_ALL = 3;
  34507. return Mesh;
  34508. }(BABYLON.AbstractMesh));
  34509. BABYLON.Mesh = Mesh;
  34510. })(BABYLON || (BABYLON = {}));
  34511. //# sourceMappingURL=babylon.mesh.js.map
  34512. var BABYLON;
  34513. (function (BABYLON) {
  34514. var BaseSubMesh = /** @class */ (function () {
  34515. function BaseSubMesh() {
  34516. }
  34517. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34518. get: function () {
  34519. return this._materialEffect;
  34520. },
  34521. enumerable: true,
  34522. configurable: true
  34523. });
  34524. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34525. if (defines === void 0) { defines = null; }
  34526. if (this._materialEffect === effect) {
  34527. if (!effect) {
  34528. this._materialDefines = null;
  34529. }
  34530. return;
  34531. }
  34532. this._materialDefines = defines;
  34533. this._materialEffect = effect;
  34534. };
  34535. return BaseSubMesh;
  34536. }());
  34537. BABYLON.BaseSubMesh = BaseSubMesh;
  34538. var SubMesh = /** @class */ (function (_super) {
  34539. __extends(SubMesh, _super);
  34540. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34541. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34542. var _this = _super.call(this) || this;
  34543. _this.materialIndex = materialIndex;
  34544. _this.verticesStart = verticesStart;
  34545. _this.verticesCount = verticesCount;
  34546. _this.indexStart = indexStart;
  34547. _this.indexCount = indexCount;
  34548. _this._renderId = 0;
  34549. _this._mesh = mesh;
  34550. _this._renderingMesh = renderingMesh || mesh;
  34551. mesh.subMeshes.push(_this);
  34552. _this._trianglePlanes = [];
  34553. _this._id = mesh.subMeshes.length - 1;
  34554. if (createBoundingBox) {
  34555. _this.refreshBoundingInfo();
  34556. mesh.computeWorldMatrix(true);
  34557. }
  34558. return _this;
  34559. }
  34560. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34561. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34562. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34563. };
  34564. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34565. get: function () {
  34566. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34567. },
  34568. enumerable: true,
  34569. configurable: true
  34570. });
  34571. /**
  34572. * Returns the submesh BoudingInfo object.
  34573. */
  34574. SubMesh.prototype.getBoundingInfo = function () {
  34575. if (this.IsGlobal) {
  34576. return this._mesh.getBoundingInfo();
  34577. }
  34578. return this._boundingInfo;
  34579. };
  34580. /**
  34581. * Sets the submesh BoundingInfo.
  34582. * Return the SubMesh.
  34583. */
  34584. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34585. this._boundingInfo = boundingInfo;
  34586. return this;
  34587. };
  34588. /**
  34589. * Returns the mesh of the current submesh.
  34590. */
  34591. SubMesh.prototype.getMesh = function () {
  34592. return this._mesh;
  34593. };
  34594. /**
  34595. * Returns the rendering mesh of the submesh.
  34596. */
  34597. SubMesh.prototype.getRenderingMesh = function () {
  34598. return this._renderingMesh;
  34599. };
  34600. /**
  34601. * Returns the submesh material.
  34602. */
  34603. SubMesh.prototype.getMaterial = function () {
  34604. var rootMaterial = this._renderingMesh.material;
  34605. if (rootMaterial === null || rootMaterial === undefined) {
  34606. return this._mesh.getScene().defaultMaterial;
  34607. }
  34608. else if (rootMaterial.getSubMaterial) {
  34609. var multiMaterial = rootMaterial;
  34610. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34611. if (this._currentMaterial !== effectiveMaterial) {
  34612. this._currentMaterial = effectiveMaterial;
  34613. this._materialDefines = null;
  34614. }
  34615. return effectiveMaterial;
  34616. }
  34617. return rootMaterial;
  34618. };
  34619. // Methods
  34620. /**
  34621. * Sets a new updated BoundingInfo object to the submesh.
  34622. * Returns the SubMesh.
  34623. */
  34624. SubMesh.prototype.refreshBoundingInfo = function () {
  34625. this._lastColliderWorldVertices = null;
  34626. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34627. return this;
  34628. }
  34629. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34630. if (!data) {
  34631. this._boundingInfo = this._mesh.getBoundingInfo();
  34632. return this;
  34633. }
  34634. var indices = this._renderingMesh.getIndices();
  34635. var extend;
  34636. //is this the only submesh?
  34637. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34638. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34639. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34640. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34641. }
  34642. else {
  34643. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34644. }
  34645. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34646. return this;
  34647. };
  34648. SubMesh.prototype._checkCollision = function (collider) {
  34649. var boundingInfo = this.getBoundingInfo();
  34650. return boundingInfo._checkCollision(collider);
  34651. };
  34652. /**
  34653. * Updates the submesh BoundingInfo.
  34654. * Returns the Submesh.
  34655. */
  34656. SubMesh.prototype.updateBoundingInfo = function (world) {
  34657. var boundingInfo = this.getBoundingInfo();
  34658. if (!boundingInfo) {
  34659. this.refreshBoundingInfo();
  34660. boundingInfo = this.getBoundingInfo();
  34661. }
  34662. boundingInfo.update(world);
  34663. return this;
  34664. };
  34665. /**
  34666. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34667. * Boolean returned.
  34668. */
  34669. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34670. var boundingInfo = this.getBoundingInfo();
  34671. if (!boundingInfo) {
  34672. return false;
  34673. }
  34674. return boundingInfo.isInFrustum(frustumPlanes);
  34675. };
  34676. /**
  34677. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34678. * Boolean returned.
  34679. */
  34680. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34681. var boundingInfo = this.getBoundingInfo();
  34682. if (!boundingInfo) {
  34683. return false;
  34684. }
  34685. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34686. };
  34687. /**
  34688. * Renders the submesh.
  34689. * Returns it.
  34690. */
  34691. SubMesh.prototype.render = function (enableAlphaMode) {
  34692. this._renderingMesh.render(this, enableAlphaMode);
  34693. return this;
  34694. };
  34695. /**
  34696. * Returns a new Index Buffer.
  34697. * Type returned : WebGLBuffer.
  34698. */
  34699. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34700. if (!this._linesIndexBuffer) {
  34701. var linesIndices = [];
  34702. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34703. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34704. }
  34705. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34706. this.linesIndexCount = linesIndices.length;
  34707. }
  34708. return this._linesIndexBuffer;
  34709. };
  34710. /**
  34711. * True is the passed Ray intersects the submesh bounding box.
  34712. * Boolean returned.
  34713. */
  34714. SubMesh.prototype.canIntersects = function (ray) {
  34715. var boundingInfo = this.getBoundingInfo();
  34716. if (!boundingInfo) {
  34717. return false;
  34718. }
  34719. return ray.intersectsBox(boundingInfo.boundingBox);
  34720. };
  34721. /**
  34722. * Returns an object IntersectionInfo.
  34723. */
  34724. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34725. var intersectInfo = null;
  34726. var material = this.getMaterial();
  34727. if (!material) {
  34728. return null;
  34729. }
  34730. switch (material.fillMode) {
  34731. case BABYLON.Material.PointListDrawMode:
  34732. case BABYLON.Material.LineListDrawMode:
  34733. case BABYLON.Material.LineLoopDrawMode:
  34734. case BABYLON.Material.LineStripDrawMode:
  34735. case BABYLON.Material.TriangleFanDrawMode:
  34736. case BABYLON.Material.TriangleStripDrawMode:
  34737. return null;
  34738. }
  34739. // LineMesh first as it's also a Mesh...
  34740. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34741. var lineMesh = this._mesh;
  34742. // Line test
  34743. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34744. var p0 = positions[indices[index]];
  34745. var p1 = positions[indices[index + 1]];
  34746. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34747. if (length < 0) {
  34748. continue;
  34749. }
  34750. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34751. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34752. if (fastCheck) {
  34753. break;
  34754. }
  34755. }
  34756. }
  34757. }
  34758. else {
  34759. // Triangles test
  34760. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34761. var p0 = positions[indices[index]];
  34762. var p1 = positions[indices[index + 1]];
  34763. var p2 = positions[indices[index + 2]];
  34764. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34765. if (currentIntersectInfo) {
  34766. if (currentIntersectInfo.distance < 0) {
  34767. continue;
  34768. }
  34769. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34770. intersectInfo = currentIntersectInfo;
  34771. intersectInfo.faceId = index / 3;
  34772. if (fastCheck) {
  34773. break;
  34774. }
  34775. }
  34776. }
  34777. }
  34778. }
  34779. return intersectInfo;
  34780. };
  34781. SubMesh.prototype._rebuild = function () {
  34782. if (this._linesIndexBuffer) {
  34783. this._linesIndexBuffer = null;
  34784. }
  34785. };
  34786. // Clone
  34787. /**
  34788. * Creates a new Submesh from the passed Mesh.
  34789. */
  34790. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34791. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34792. if (!this.IsGlobal) {
  34793. var boundingInfo = this.getBoundingInfo();
  34794. if (!boundingInfo) {
  34795. return result;
  34796. }
  34797. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34798. }
  34799. return result;
  34800. };
  34801. // Dispose
  34802. /**
  34803. * Disposes the Submesh.
  34804. * Returns nothing.
  34805. */
  34806. SubMesh.prototype.dispose = function () {
  34807. if (this._linesIndexBuffer) {
  34808. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34809. this._linesIndexBuffer = null;
  34810. }
  34811. // Remove from mesh
  34812. var index = this._mesh.subMeshes.indexOf(this);
  34813. this._mesh.subMeshes.splice(index, 1);
  34814. };
  34815. // Statics
  34816. /**
  34817. * Creates a new Submesh from the passed parameters :
  34818. * - materialIndex (integer) : the index of the main mesh material.
  34819. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34820. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34821. * - mesh (Mesh) : the main mesh to create the submesh from.
  34822. * - renderingMesh (optional Mesh) : rendering mesh.
  34823. */
  34824. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34825. var minVertexIndex = Number.MAX_VALUE;
  34826. var maxVertexIndex = -Number.MAX_VALUE;
  34827. renderingMesh = (renderingMesh || mesh);
  34828. var indices = renderingMesh.getIndices();
  34829. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34830. var vertexIndex = indices[index];
  34831. if (vertexIndex < minVertexIndex)
  34832. minVertexIndex = vertexIndex;
  34833. if (vertexIndex > maxVertexIndex)
  34834. maxVertexIndex = vertexIndex;
  34835. }
  34836. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34837. };
  34838. return SubMesh;
  34839. }(BaseSubMesh));
  34840. BABYLON.SubMesh = SubMesh;
  34841. })(BABYLON || (BABYLON = {}));
  34842. //# sourceMappingURL=babylon.subMesh.js.map
  34843. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34844. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34845. s = arguments[i];
  34846. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34847. t[p] = s[p];
  34848. }
  34849. return t;
  34850. };
  34851. var BABYLON;
  34852. (function (BABYLON) {
  34853. /**
  34854. * Manages the defines for the Material
  34855. */
  34856. var MaterialDefines = /** @class */ (function () {
  34857. function MaterialDefines() {
  34858. this._isDirty = true;
  34859. /** @hidden */
  34860. this._areLightsDirty = true;
  34861. /** @hidden */
  34862. this._areAttributesDirty = true;
  34863. /** @hidden */
  34864. this._areTexturesDirty = true;
  34865. /** @hidden */
  34866. this._areFresnelDirty = true;
  34867. /** @hidden */
  34868. this._areMiscDirty = true;
  34869. /** @hidden */
  34870. this._areImageProcessingDirty = true;
  34871. /** @hidden */
  34872. this._normals = false;
  34873. /** @hidden */
  34874. this._uvs = false;
  34875. /** @hidden */
  34876. this._needNormals = false;
  34877. /** @hidden */
  34878. this._needUVs = false;
  34879. }
  34880. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34881. /**
  34882. * Specifies if the material needs to be re-calculated
  34883. */
  34884. get: function () {
  34885. return this._isDirty;
  34886. },
  34887. enumerable: true,
  34888. configurable: true
  34889. });
  34890. /**
  34891. * Marks the material to indicate that it has been re-calculated
  34892. */
  34893. MaterialDefines.prototype.markAsProcessed = function () {
  34894. this._isDirty = false;
  34895. this._areAttributesDirty = false;
  34896. this._areTexturesDirty = false;
  34897. this._areFresnelDirty = false;
  34898. this._areLightsDirty = false;
  34899. this._areMiscDirty = false;
  34900. this._areImageProcessingDirty = false;
  34901. };
  34902. /**
  34903. * Marks the material to indicate that it needs to be re-calculated
  34904. */
  34905. MaterialDefines.prototype.markAsUnprocessed = function () {
  34906. this._isDirty = true;
  34907. };
  34908. /**
  34909. * Marks the material to indicate all of its defines need to be re-calculated
  34910. */
  34911. MaterialDefines.prototype.markAllAsDirty = function () {
  34912. this._areTexturesDirty = true;
  34913. this._areAttributesDirty = true;
  34914. this._areLightsDirty = true;
  34915. this._areFresnelDirty = true;
  34916. this._areMiscDirty = true;
  34917. this._areImageProcessingDirty = true;
  34918. this._isDirty = true;
  34919. };
  34920. /**
  34921. * Marks the material to indicate that image processing needs to be re-calculated
  34922. */
  34923. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34924. this._areImageProcessingDirty = true;
  34925. this._isDirty = true;
  34926. };
  34927. /**
  34928. * Marks the material to indicate the lights need to be re-calculated
  34929. */
  34930. MaterialDefines.prototype.markAsLightDirty = function () {
  34931. this._areLightsDirty = true;
  34932. this._isDirty = true;
  34933. };
  34934. /**
  34935. * Marks the attribute state as changed
  34936. */
  34937. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34938. this._areAttributesDirty = true;
  34939. this._isDirty = true;
  34940. };
  34941. /**
  34942. * Marks the texture state as changed
  34943. */
  34944. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34945. this._areTexturesDirty = true;
  34946. this._isDirty = true;
  34947. };
  34948. /**
  34949. * Marks the fresnel state as changed
  34950. */
  34951. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34952. this._areFresnelDirty = true;
  34953. this._isDirty = true;
  34954. };
  34955. /**
  34956. * Marks the misc state as changed
  34957. */
  34958. MaterialDefines.prototype.markAsMiscDirty = function () {
  34959. this._areMiscDirty = true;
  34960. this._isDirty = true;
  34961. };
  34962. /**
  34963. * Rebuilds the material defines
  34964. */
  34965. MaterialDefines.prototype.rebuild = function () {
  34966. if (this._keys) {
  34967. delete this._keys;
  34968. }
  34969. this._keys = [];
  34970. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34971. var key = _a[_i];
  34972. if (key[0] === "_") {
  34973. continue;
  34974. }
  34975. this._keys.push(key);
  34976. }
  34977. };
  34978. /**
  34979. * Specifies if two material defines are equal
  34980. * @param other - A material define instance to compare to
  34981. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34982. */
  34983. MaterialDefines.prototype.isEqual = function (other) {
  34984. if (this._keys.length !== other._keys.length) {
  34985. return false;
  34986. }
  34987. for (var index = 0; index < this._keys.length; index++) {
  34988. var prop = this._keys[index];
  34989. if (this[prop] !== other[prop]) {
  34990. return false;
  34991. }
  34992. }
  34993. return true;
  34994. };
  34995. /**
  34996. * Clones this instance's defines to another instance
  34997. * @param other - material defines to clone values to
  34998. */
  34999. MaterialDefines.prototype.cloneTo = function (other) {
  35000. if (this._keys.length !== other._keys.length) {
  35001. other._keys = this._keys.slice(0);
  35002. }
  35003. for (var index = 0; index < this._keys.length; index++) {
  35004. var prop = this._keys[index];
  35005. other[prop] = this[prop];
  35006. }
  35007. };
  35008. /**
  35009. * Resets the material define values
  35010. */
  35011. MaterialDefines.prototype.reset = function () {
  35012. for (var index = 0; index < this._keys.length; index++) {
  35013. var prop = this._keys[index];
  35014. var type = typeof this[prop];
  35015. switch (type) {
  35016. case "number":
  35017. this[prop] = 0;
  35018. break;
  35019. case "string":
  35020. this[prop] = "";
  35021. break;
  35022. default:
  35023. this[prop] = false;
  35024. break;
  35025. }
  35026. }
  35027. };
  35028. /**
  35029. * Converts the material define values to a string
  35030. * @returns - String of material define information
  35031. */
  35032. MaterialDefines.prototype.toString = function () {
  35033. var result = "";
  35034. for (var index = 0; index < this._keys.length; index++) {
  35035. var prop = this._keys[index];
  35036. var value = this[prop];
  35037. var type = typeof value;
  35038. switch (type) {
  35039. case "number":
  35040. case "string":
  35041. result += "#define " + prop + " " + value + "\n";
  35042. break;
  35043. default:
  35044. if (value) {
  35045. result += "#define " + prop + "\n";
  35046. }
  35047. break;
  35048. }
  35049. }
  35050. return result;
  35051. };
  35052. return MaterialDefines;
  35053. }());
  35054. BABYLON.MaterialDefines = MaterialDefines;
  35055. /**
  35056. * Base class for the main features of a material in Babylon.js
  35057. */
  35058. var Material = /** @class */ (function () {
  35059. /**
  35060. * Creates a material instance
  35061. * @param name defines the name of the material
  35062. * @param scene defines the scene to reference
  35063. * @param doNotAdd specifies if the material should be added to the scene
  35064. */
  35065. function Material(name, scene, doNotAdd) {
  35066. /**
  35067. * Specifies if the ready state should be checked on each call
  35068. */
  35069. this.checkReadyOnEveryCall = false;
  35070. /**
  35071. * Specifies if the ready state should be checked once
  35072. */
  35073. this.checkReadyOnlyOnce = false;
  35074. /**
  35075. * The state of the material
  35076. */
  35077. this.state = "";
  35078. /**
  35079. * The alpha value of the material
  35080. */
  35081. this._alpha = 1.0;
  35082. /**
  35083. * Specifies if back face culling is enabled
  35084. */
  35085. this._backFaceCulling = true;
  35086. /**
  35087. * Specifies if the material should be serialized
  35088. */
  35089. this.doNotSerialize = false;
  35090. /**
  35091. * Specifies if the effect should be stored on sub meshes
  35092. */
  35093. this.storeEffectOnSubMeshes = false;
  35094. /**
  35095. * An event triggered when the material is disposed
  35096. */
  35097. this.onDisposeObservable = new BABYLON.Observable();
  35098. /**
  35099. * An event triggered when the material is bound
  35100. */
  35101. this.onBindObservable = new BABYLON.Observable();
  35102. /**
  35103. * An event triggered when the material is unbound
  35104. */
  35105. this.onUnBindObservable = new BABYLON.Observable();
  35106. /**
  35107. * Stores the value of the alpha mode
  35108. */
  35109. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35110. /**
  35111. * Stores the state of the need depth pre-pass value
  35112. */
  35113. this._needDepthPrePass = false;
  35114. /**
  35115. * Specifies if depth writing should be disabled
  35116. */
  35117. this.disableDepthWrite = false;
  35118. /**
  35119. * Specifies if depth writing should be forced
  35120. */
  35121. this.forceDepthWrite = false;
  35122. /**
  35123. * Specifies if there should be a separate pass for culling
  35124. */
  35125. this.separateCullingPass = false;
  35126. /**
  35127. * Stores the state specifing if fog should be enabled
  35128. */
  35129. this._fogEnabled = true;
  35130. /**
  35131. * Stores the size of points
  35132. */
  35133. this.pointSize = 1.0;
  35134. /**
  35135. * Stores the z offset value
  35136. */
  35137. this.zOffset = 0;
  35138. /**
  35139. * Specifies if the material was previously ready
  35140. */
  35141. this._wasPreviouslyReady = false;
  35142. /**
  35143. * Stores the fill mode state
  35144. */
  35145. this._fillMode = Material.TriangleFillMode;
  35146. this.name = name;
  35147. this.id = name || BABYLON.Tools.RandomId();
  35148. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35149. this.uniqueId = this._scene.getUniqueId();
  35150. if (this._scene.useRightHandedSystem) {
  35151. this.sideOrientation = Material.ClockWiseSideOrientation;
  35152. }
  35153. else {
  35154. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35155. }
  35156. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35157. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35158. if (!doNotAdd) {
  35159. this._scene.materials.push(this);
  35160. }
  35161. }
  35162. Object.defineProperty(Material, "TriangleFillMode", {
  35163. /**
  35164. * Returns the triangle fill mode
  35165. */
  35166. get: function () {
  35167. return Material._TriangleFillMode;
  35168. },
  35169. enumerable: true,
  35170. configurable: true
  35171. });
  35172. Object.defineProperty(Material, "WireFrameFillMode", {
  35173. /**
  35174. * Returns the wireframe mode
  35175. */
  35176. get: function () {
  35177. return Material._WireFrameFillMode;
  35178. },
  35179. enumerable: true,
  35180. configurable: true
  35181. });
  35182. Object.defineProperty(Material, "PointFillMode", {
  35183. /**
  35184. * Returns the point fill mode
  35185. */
  35186. get: function () {
  35187. return Material._PointFillMode;
  35188. },
  35189. enumerable: true,
  35190. configurable: true
  35191. });
  35192. Object.defineProperty(Material, "PointListDrawMode", {
  35193. /**
  35194. * Returns the point list draw mode
  35195. */
  35196. get: function () {
  35197. return Material._PointListDrawMode;
  35198. },
  35199. enumerable: true,
  35200. configurable: true
  35201. });
  35202. Object.defineProperty(Material, "LineListDrawMode", {
  35203. /**
  35204. * Returns the line list draw mode
  35205. */
  35206. get: function () {
  35207. return Material._LineListDrawMode;
  35208. },
  35209. enumerable: true,
  35210. configurable: true
  35211. });
  35212. Object.defineProperty(Material, "LineLoopDrawMode", {
  35213. /**
  35214. * Returns the line loop draw mode
  35215. */
  35216. get: function () {
  35217. return Material._LineLoopDrawMode;
  35218. },
  35219. enumerable: true,
  35220. configurable: true
  35221. });
  35222. Object.defineProperty(Material, "LineStripDrawMode", {
  35223. /**
  35224. * Returns the line strip draw mode
  35225. */
  35226. get: function () {
  35227. return Material._LineStripDrawMode;
  35228. },
  35229. enumerable: true,
  35230. configurable: true
  35231. });
  35232. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35233. /**
  35234. * Returns the triangle strip draw mode
  35235. */
  35236. get: function () {
  35237. return Material._TriangleStripDrawMode;
  35238. },
  35239. enumerable: true,
  35240. configurable: true
  35241. });
  35242. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35243. /**
  35244. * Returns the triangle fan draw mode
  35245. */
  35246. get: function () {
  35247. return Material._TriangleFanDrawMode;
  35248. },
  35249. enumerable: true,
  35250. configurable: true
  35251. });
  35252. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35253. /**
  35254. * Returns the clock-wise side orientation
  35255. */
  35256. get: function () {
  35257. return Material._ClockWiseSideOrientation;
  35258. },
  35259. enumerable: true,
  35260. configurable: true
  35261. });
  35262. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35263. /**
  35264. * Returns the counter clock-wise side orientation
  35265. */
  35266. get: function () {
  35267. return Material._CounterClockWiseSideOrientation;
  35268. },
  35269. enumerable: true,
  35270. configurable: true
  35271. });
  35272. Object.defineProperty(Material, "TextureDirtyFlag", {
  35273. /**
  35274. * Returns the dirty texture flag value
  35275. */
  35276. get: function () {
  35277. return Material._TextureDirtyFlag;
  35278. },
  35279. enumerable: true,
  35280. configurable: true
  35281. });
  35282. Object.defineProperty(Material, "LightDirtyFlag", {
  35283. /**
  35284. * Returns the dirty light flag value
  35285. */
  35286. get: function () {
  35287. return Material._LightDirtyFlag;
  35288. },
  35289. enumerable: true,
  35290. configurable: true
  35291. });
  35292. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35293. /**
  35294. * Returns the dirty fresnel flag value
  35295. */
  35296. get: function () {
  35297. return Material._FresnelDirtyFlag;
  35298. },
  35299. enumerable: true,
  35300. configurable: true
  35301. });
  35302. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35303. /**
  35304. * Returns the dirty attributes flag value
  35305. */
  35306. get: function () {
  35307. return Material._AttributesDirtyFlag;
  35308. },
  35309. enumerable: true,
  35310. configurable: true
  35311. });
  35312. Object.defineProperty(Material, "MiscDirtyFlag", {
  35313. /**
  35314. * Returns the dirty misc flag value
  35315. */
  35316. get: function () {
  35317. return Material._MiscDirtyFlag;
  35318. },
  35319. enumerable: true,
  35320. configurable: true
  35321. });
  35322. Object.defineProperty(Material.prototype, "alpha", {
  35323. /**
  35324. * Gets the alpha value of the material
  35325. */
  35326. get: function () {
  35327. return this._alpha;
  35328. },
  35329. /**
  35330. * Sets the alpha value of the material
  35331. */
  35332. set: function (value) {
  35333. if (this._alpha === value) {
  35334. return;
  35335. }
  35336. this._alpha = value;
  35337. this.markAsDirty(Material.MiscDirtyFlag);
  35338. },
  35339. enumerable: true,
  35340. configurable: true
  35341. });
  35342. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35343. /**
  35344. * Gets the back-face culling state
  35345. */
  35346. get: function () {
  35347. return this._backFaceCulling;
  35348. },
  35349. /**
  35350. * Sets the back-face culling state
  35351. */
  35352. set: function (value) {
  35353. if (this._backFaceCulling === value) {
  35354. return;
  35355. }
  35356. this._backFaceCulling = value;
  35357. this.markAsDirty(Material.TextureDirtyFlag);
  35358. },
  35359. enumerable: true,
  35360. configurable: true
  35361. });
  35362. Object.defineProperty(Material.prototype, "onDispose", {
  35363. /**
  35364. * Called during a dispose event
  35365. */
  35366. set: function (callback) {
  35367. if (this._onDisposeObserver) {
  35368. this.onDisposeObservable.remove(this._onDisposeObserver);
  35369. }
  35370. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35371. },
  35372. enumerable: true,
  35373. configurable: true
  35374. });
  35375. Object.defineProperty(Material.prototype, "onBind", {
  35376. /**
  35377. * Called during a bind event
  35378. */
  35379. set: function (callback) {
  35380. if (this._onBindObserver) {
  35381. this.onBindObservable.remove(this._onBindObserver);
  35382. }
  35383. this._onBindObserver = this.onBindObservable.add(callback);
  35384. },
  35385. enumerable: true,
  35386. configurable: true
  35387. });
  35388. Object.defineProperty(Material.prototype, "alphaMode", {
  35389. /**
  35390. * Gets the value of the alpha mode
  35391. */
  35392. get: function () {
  35393. return this._alphaMode;
  35394. },
  35395. /**
  35396. * Sets the value of the alpha mode.
  35397. *
  35398. * | Value | Type | Description |
  35399. * | --- | --- | --- |
  35400. * | 0 | ALPHA_DISABLE | |
  35401. * | 1 | ALPHA_ADD | |
  35402. * | 2 | ALPHA_COMBINE | |
  35403. * | 3 | ALPHA_SUBTRACT | |
  35404. * | 4 | ALPHA_MULTIPLY | |
  35405. * | 5 | ALPHA_MAXIMIZED | |
  35406. * | 6 | ALPHA_ONEONE | |
  35407. * | 7 | ALPHA_PREMULTIPLIED | |
  35408. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35409. * | 9 | ALPHA_INTERPOLATE | |
  35410. * | 10 | ALPHA_SCREENMODE | |
  35411. *
  35412. */
  35413. set: function (value) {
  35414. if (this._alphaMode === value) {
  35415. return;
  35416. }
  35417. this._alphaMode = value;
  35418. this.markAsDirty(Material.TextureDirtyFlag);
  35419. },
  35420. enumerable: true,
  35421. configurable: true
  35422. });
  35423. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35424. /**
  35425. * Gets the depth pre-pass value
  35426. */
  35427. get: function () {
  35428. return this._needDepthPrePass;
  35429. },
  35430. /**
  35431. * Sets the need depth pre-pass value
  35432. */
  35433. set: function (value) {
  35434. if (this._needDepthPrePass === value) {
  35435. return;
  35436. }
  35437. this._needDepthPrePass = value;
  35438. if (this._needDepthPrePass) {
  35439. this.checkReadyOnEveryCall = true;
  35440. }
  35441. },
  35442. enumerable: true,
  35443. configurable: true
  35444. });
  35445. Object.defineProperty(Material.prototype, "fogEnabled", {
  35446. /**
  35447. * Gets the value of the fog enabled state
  35448. */
  35449. get: function () {
  35450. return this._fogEnabled;
  35451. },
  35452. /**
  35453. * Sets the state for enabling fog
  35454. */
  35455. set: function (value) {
  35456. if (this._fogEnabled === value) {
  35457. return;
  35458. }
  35459. this._fogEnabled = value;
  35460. this.markAsDirty(Material.MiscDirtyFlag);
  35461. },
  35462. enumerable: true,
  35463. configurable: true
  35464. });
  35465. Object.defineProperty(Material.prototype, "wireframe", {
  35466. /**
  35467. * Gets a value specifying if wireframe mode is enabled
  35468. */
  35469. get: function () {
  35470. switch (this._fillMode) {
  35471. case Material.WireFrameFillMode:
  35472. case Material.LineListDrawMode:
  35473. case Material.LineLoopDrawMode:
  35474. case Material.LineStripDrawMode:
  35475. return true;
  35476. }
  35477. return this._scene.forceWireframe;
  35478. },
  35479. /**
  35480. * Sets the state of wireframe mode
  35481. */
  35482. set: function (value) {
  35483. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35484. },
  35485. enumerable: true,
  35486. configurable: true
  35487. });
  35488. Object.defineProperty(Material.prototype, "pointsCloud", {
  35489. /**
  35490. * Gets the value specifying if point clouds are enabled
  35491. */
  35492. get: function () {
  35493. switch (this._fillMode) {
  35494. case Material.PointFillMode:
  35495. case Material.PointListDrawMode:
  35496. return true;
  35497. }
  35498. return this._scene.forcePointsCloud;
  35499. },
  35500. /**
  35501. * Sets the state of point cloud mode
  35502. */
  35503. set: function (value) {
  35504. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35505. },
  35506. enumerable: true,
  35507. configurable: true
  35508. });
  35509. Object.defineProperty(Material.prototype, "fillMode", {
  35510. /**
  35511. * Gets the material fill mode
  35512. */
  35513. get: function () {
  35514. return this._fillMode;
  35515. },
  35516. /**
  35517. * Sets the material fill mode
  35518. */
  35519. set: function (value) {
  35520. if (this._fillMode === value) {
  35521. return;
  35522. }
  35523. this._fillMode = value;
  35524. this.markAsDirty(Material.MiscDirtyFlag);
  35525. },
  35526. enumerable: true,
  35527. configurable: true
  35528. });
  35529. /**
  35530. * Returns a string representation of the current material
  35531. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35532. * @returns a string with material information
  35533. */
  35534. Material.prototype.toString = function (fullDetails) {
  35535. var ret = "Name: " + this.name;
  35536. if (fullDetails) {
  35537. }
  35538. return ret;
  35539. };
  35540. /**
  35541. * Gets the class name of the material
  35542. * @returns a string with the class name of the material
  35543. */
  35544. Material.prototype.getClassName = function () {
  35545. return "Material";
  35546. };
  35547. Object.defineProperty(Material.prototype, "isFrozen", {
  35548. /**
  35549. * Specifies if updates for the material been locked
  35550. */
  35551. get: function () {
  35552. return this.checkReadyOnlyOnce;
  35553. },
  35554. enumerable: true,
  35555. configurable: true
  35556. });
  35557. /**
  35558. * Locks updates for the material
  35559. */
  35560. Material.prototype.freeze = function () {
  35561. this.checkReadyOnlyOnce = true;
  35562. };
  35563. /**
  35564. * Unlocks updates for the material
  35565. */
  35566. Material.prototype.unfreeze = function () {
  35567. this.checkReadyOnlyOnce = false;
  35568. };
  35569. /**
  35570. * Specifies if the material is ready to be used
  35571. * @param mesh defines the mesh to check
  35572. * @param useInstances specifies if instances should be used
  35573. * @returns a boolean indicating if the material is ready to be used
  35574. */
  35575. Material.prototype.isReady = function (mesh, useInstances) {
  35576. return true;
  35577. };
  35578. /**
  35579. * Specifies that the submesh is ready to be used
  35580. * @param mesh defines the mesh to check
  35581. * @param subMesh defines which submesh to check
  35582. * @param useInstances specifies that instances should be used
  35583. * @returns a boolean indicating that the submesh is ready or not
  35584. */
  35585. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35586. return false;
  35587. };
  35588. /**
  35589. * Returns the material effect
  35590. * @returns the effect associated with the material
  35591. */
  35592. Material.prototype.getEffect = function () {
  35593. return this._effect;
  35594. };
  35595. /**
  35596. * Returns the current scene
  35597. * @returns a Scene
  35598. */
  35599. Material.prototype.getScene = function () {
  35600. return this._scene;
  35601. };
  35602. /**
  35603. * Specifies if the material will require alpha blending
  35604. * @returns a boolean specifying if alpha blending is needed
  35605. */
  35606. Material.prototype.needAlphaBlending = function () {
  35607. return (this.alpha < 1.0);
  35608. };
  35609. /**
  35610. * Specifies if the mesh will require alpha blending
  35611. * @param mesh defines the mesh to check
  35612. * @returns a boolean specifying if alpha blending is needed for the mesh
  35613. */
  35614. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35615. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35616. };
  35617. /**
  35618. * Specifies if this material should be rendered in alpha test mode
  35619. * @returns a boolean specifying if an alpha test is needed.
  35620. */
  35621. Material.prototype.needAlphaTesting = function () {
  35622. return false;
  35623. };
  35624. /**
  35625. * Gets the texture used for the alpha test
  35626. * @returns the texture to use for alpha testing
  35627. */
  35628. Material.prototype.getAlphaTestTexture = function () {
  35629. return null;
  35630. };
  35631. /**
  35632. * Marks the material to indicate that it needs to be re-calculated
  35633. */
  35634. Material.prototype.markDirty = function () {
  35635. this._wasPreviouslyReady = false;
  35636. };
  35637. /** @hidden */
  35638. Material.prototype._preBind = function (effect, overrideOrientation) {
  35639. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35640. var engine = this._scene.getEngine();
  35641. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35642. var reverse = orientation === Material.ClockWiseSideOrientation;
  35643. engine.enableEffect(effect ? effect : this._effect);
  35644. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35645. return reverse;
  35646. };
  35647. /**
  35648. * Binds the material to the mesh
  35649. * @param world defines the world transformation matrix
  35650. * @param mesh defines the mesh to bind the material to
  35651. */
  35652. Material.prototype.bind = function (world, mesh) {
  35653. };
  35654. /**
  35655. * Binds the submesh to the material
  35656. * @param world defines the world transformation matrix
  35657. * @param mesh defines the mesh containing the submesh
  35658. * @param subMesh defines the submesh to bind the material to
  35659. */
  35660. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35661. };
  35662. /**
  35663. * Binds the world matrix to the material
  35664. * @param world defines the world transformation matrix
  35665. */
  35666. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35667. };
  35668. /**
  35669. * Binds the scene's uniform buffer to the effect.
  35670. * @param effect defines the effect to bind to the scene uniform buffer
  35671. * @param sceneUbo defines the uniform buffer storing scene data
  35672. */
  35673. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35674. sceneUbo.bindToEffect(effect, "Scene");
  35675. };
  35676. /**
  35677. * Binds the view matrix to the effect
  35678. * @param effect defines the effect to bind the view matrix to
  35679. */
  35680. Material.prototype.bindView = function (effect) {
  35681. if (!this._useUBO) {
  35682. effect.setMatrix("view", this.getScene().getViewMatrix());
  35683. }
  35684. else {
  35685. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35686. }
  35687. };
  35688. /**
  35689. * Binds the view projection matrix to the effect
  35690. * @param effect defines the effect to bind the view projection matrix to
  35691. */
  35692. Material.prototype.bindViewProjection = function (effect) {
  35693. if (!this._useUBO) {
  35694. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35695. }
  35696. else {
  35697. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35698. }
  35699. };
  35700. /**
  35701. * Specifies if material alpha testing should be turned on for the mesh
  35702. * @param mesh defines the mesh to check
  35703. */
  35704. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35705. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35706. };
  35707. /**
  35708. * Processes to execute after binding the material to a mesh
  35709. * @param mesh defines the rendered mesh
  35710. */
  35711. Material.prototype._afterBind = function (mesh) {
  35712. this._scene._cachedMaterial = this;
  35713. if (mesh) {
  35714. this._scene._cachedVisibility = mesh.visibility;
  35715. }
  35716. else {
  35717. this._scene._cachedVisibility = 1;
  35718. }
  35719. if (mesh) {
  35720. this.onBindObservable.notifyObservers(mesh);
  35721. }
  35722. if (this.disableDepthWrite) {
  35723. var engine = this._scene.getEngine();
  35724. this._cachedDepthWriteState = engine.getDepthWrite();
  35725. engine.setDepthWrite(false);
  35726. }
  35727. };
  35728. /**
  35729. * Unbinds the material from the mesh
  35730. */
  35731. Material.prototype.unbind = function () {
  35732. this.onUnBindObservable.notifyObservers(this);
  35733. if (this.disableDepthWrite) {
  35734. var engine = this._scene.getEngine();
  35735. engine.setDepthWrite(this._cachedDepthWriteState);
  35736. }
  35737. };
  35738. /**
  35739. * Gets the active textures from the material
  35740. * @returns an array of textures
  35741. */
  35742. Material.prototype.getActiveTextures = function () {
  35743. return [];
  35744. };
  35745. /**
  35746. * Specifies if the material uses a texture
  35747. * @param texture defines the texture to check against the material
  35748. * @returns a boolean specifying if the material uses the texture
  35749. */
  35750. Material.prototype.hasTexture = function (texture) {
  35751. return false;
  35752. };
  35753. /**
  35754. * Makes a duplicate of the material, and gives it a new name
  35755. * @param name defines the new name for the duplicated material
  35756. * @returns the cloned material
  35757. */
  35758. Material.prototype.clone = function (name) {
  35759. return null;
  35760. };
  35761. /**
  35762. * Gets the meshes bound to the material
  35763. * @returns an array of meshes bound to the material
  35764. */
  35765. Material.prototype.getBindedMeshes = function () {
  35766. var result = new Array();
  35767. for (var index = 0; index < this._scene.meshes.length; index++) {
  35768. var mesh = this._scene.meshes[index];
  35769. if (mesh.material === this) {
  35770. result.push(mesh);
  35771. }
  35772. }
  35773. return result;
  35774. };
  35775. /**
  35776. * Force shader compilation
  35777. * @param mesh defines the mesh associated with this material
  35778. * @param onCompiled defines a function to execute once the material is compiled
  35779. * @param options defines the options to configure the compilation
  35780. */
  35781. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35782. var _this = this;
  35783. var localOptions = __assign({ clipPlane: false }, options);
  35784. var subMesh = new BABYLON.BaseSubMesh();
  35785. var scene = this.getScene();
  35786. var checkReady = function () {
  35787. if (!_this._scene || !_this._scene.getEngine()) {
  35788. return;
  35789. }
  35790. if (subMesh._materialDefines) {
  35791. subMesh._materialDefines._renderId = -1;
  35792. }
  35793. var clipPlaneState = scene.clipPlane;
  35794. if (localOptions.clipPlane) {
  35795. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35796. }
  35797. if (_this.storeEffectOnSubMeshes) {
  35798. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35799. if (onCompiled) {
  35800. onCompiled(_this);
  35801. }
  35802. }
  35803. else {
  35804. setTimeout(checkReady, 16);
  35805. }
  35806. }
  35807. else {
  35808. if (_this.isReady(mesh)) {
  35809. if (onCompiled) {
  35810. onCompiled(_this);
  35811. }
  35812. }
  35813. else {
  35814. setTimeout(checkReady, 16);
  35815. }
  35816. }
  35817. if (localOptions.clipPlane) {
  35818. scene.clipPlane = clipPlaneState;
  35819. }
  35820. };
  35821. checkReady();
  35822. };
  35823. /**
  35824. * Force shader compilation
  35825. * @param mesh defines the mesh that will use this material
  35826. * @param options defines additional options for compiling the shaders
  35827. * @returns a promise that resolves when the compilation completes
  35828. */
  35829. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35830. var _this = this;
  35831. return new Promise(function (resolve) {
  35832. _this.forceCompilation(mesh, function () {
  35833. resolve();
  35834. }, options);
  35835. });
  35836. };
  35837. /**
  35838. * Marks a define in the material to indicate that it needs to be re-computed
  35839. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35840. */
  35841. Material.prototype.markAsDirty = function (flag) {
  35842. if (flag & Material.TextureDirtyFlag) {
  35843. this._markAllSubMeshesAsTexturesDirty();
  35844. }
  35845. if (flag & Material.LightDirtyFlag) {
  35846. this._markAllSubMeshesAsLightsDirty();
  35847. }
  35848. if (flag & Material.FresnelDirtyFlag) {
  35849. this._markAllSubMeshesAsFresnelDirty();
  35850. }
  35851. if (flag & Material.AttributesDirtyFlag) {
  35852. this._markAllSubMeshesAsAttributesDirty();
  35853. }
  35854. if (flag & Material.MiscDirtyFlag) {
  35855. this._markAllSubMeshesAsMiscDirty();
  35856. }
  35857. this.getScene().resetCachedMaterial();
  35858. };
  35859. /**
  35860. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35861. * @param func defines a function which checks material defines against the submeshes
  35862. */
  35863. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35864. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35865. var mesh = _a[_i];
  35866. if (!mesh.subMeshes) {
  35867. continue;
  35868. }
  35869. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35870. var subMesh = _c[_b];
  35871. if (subMesh.getMaterial() !== this) {
  35872. continue;
  35873. }
  35874. if (!subMesh._materialDefines) {
  35875. continue;
  35876. }
  35877. func(subMesh._materialDefines);
  35878. }
  35879. }
  35880. };
  35881. /**
  35882. * Indicates that image processing needs to be re-calculated for all submeshes
  35883. */
  35884. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35885. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35886. };
  35887. /**
  35888. * Indicates that textures need to be re-calculated for all submeshes
  35889. */
  35890. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35891. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35892. };
  35893. /**
  35894. * Indicates that fresnel needs to be re-calculated for all submeshes
  35895. */
  35896. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35897. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35898. };
  35899. /**
  35900. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35901. */
  35902. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35903. this._markAllSubMeshesAsDirty(function (defines) {
  35904. defines.markAsFresnelDirty();
  35905. defines.markAsMiscDirty();
  35906. });
  35907. };
  35908. /**
  35909. * Indicates that lights need to be re-calculated for all submeshes
  35910. */
  35911. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35912. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35913. };
  35914. /**
  35915. * Indicates that attributes need to be re-calculated for all submeshes
  35916. */
  35917. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35918. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35919. };
  35920. /**
  35921. * Indicates that misc needs to be re-calculated for all submeshes
  35922. */
  35923. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35924. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35925. };
  35926. /**
  35927. * Indicates that textures and misc need to be re-calculated for all submeshes
  35928. */
  35929. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35930. this._markAllSubMeshesAsDirty(function (defines) {
  35931. defines.markAsTexturesDirty();
  35932. defines.markAsMiscDirty();
  35933. });
  35934. };
  35935. /**
  35936. * Disposes the material
  35937. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35938. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35939. */
  35940. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35941. // Animations
  35942. this.getScene().stopAnimation(this);
  35943. this.getScene().freeProcessedMaterials();
  35944. // Remove from scene
  35945. var index = this._scene.materials.indexOf(this);
  35946. if (index >= 0) {
  35947. this._scene.materials.splice(index, 1);
  35948. }
  35949. // Remove from meshes
  35950. for (index = 0; index < this._scene.meshes.length; index++) {
  35951. var mesh = this._scene.meshes[index];
  35952. if (mesh.material === this) {
  35953. mesh.material = null;
  35954. if (mesh.geometry) {
  35955. var geometry = (mesh.geometry);
  35956. if (this.storeEffectOnSubMeshes) {
  35957. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35958. var subMesh = _a[_i];
  35959. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35960. if (forceDisposeEffect && subMesh._materialEffect) {
  35961. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35962. }
  35963. }
  35964. }
  35965. else {
  35966. geometry._releaseVertexArrayObject(this._effect);
  35967. }
  35968. }
  35969. }
  35970. }
  35971. this._uniformBuffer.dispose();
  35972. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35973. if (forceDisposeEffect && this._effect) {
  35974. if (!this.storeEffectOnSubMeshes) {
  35975. this._scene.getEngine()._releaseEffect(this._effect);
  35976. }
  35977. this._effect = null;
  35978. }
  35979. // Callback
  35980. this.onDisposeObservable.notifyObservers(this);
  35981. this.onDisposeObservable.clear();
  35982. this.onBindObservable.clear();
  35983. this.onUnBindObservable.clear();
  35984. };
  35985. /**
  35986. * Serializes this material
  35987. * @returns the serialized material object
  35988. */
  35989. Material.prototype.serialize = function () {
  35990. return BABYLON.SerializationHelper.Serialize(this);
  35991. };
  35992. /**
  35993. * Creates a MultiMaterial from parsed MultiMaterial data.
  35994. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35995. * @param scene defines the hosting scene
  35996. * @returns a new MultiMaterial
  35997. */
  35998. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35999. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36000. multiMaterial.id = parsedMultiMaterial.id;
  36001. if (BABYLON.Tags) {
  36002. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36003. }
  36004. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36005. var subMatId = parsedMultiMaterial.materials[matIndex];
  36006. if (subMatId) {
  36007. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36008. }
  36009. else {
  36010. multiMaterial.subMaterials.push(null);
  36011. }
  36012. }
  36013. return multiMaterial;
  36014. };
  36015. /**
  36016. * Creates a material from parsed material data
  36017. * @param parsedMaterial defines parsed material data
  36018. * @param scene defines the hosting scene
  36019. * @param rootUrl defines the root URL to use to load textures
  36020. * @returns a new material
  36021. */
  36022. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36023. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36024. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36025. }
  36026. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36027. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36028. if (!BABYLON.LegacyPBRMaterial) {
  36029. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36030. return;
  36031. }
  36032. }
  36033. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36034. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36035. };
  36036. // Triangle views
  36037. Material._TriangleFillMode = 0;
  36038. Material._WireFrameFillMode = 1;
  36039. Material._PointFillMode = 2;
  36040. // Draw modes
  36041. Material._PointListDrawMode = 3;
  36042. Material._LineListDrawMode = 4;
  36043. Material._LineLoopDrawMode = 5;
  36044. Material._LineStripDrawMode = 6;
  36045. Material._TriangleStripDrawMode = 7;
  36046. Material._TriangleFanDrawMode = 8;
  36047. /**
  36048. * Stores the clock-wise side orientation
  36049. */
  36050. Material._ClockWiseSideOrientation = 0;
  36051. /**
  36052. * Stores the counter clock-wise side orientation
  36053. */
  36054. Material._CounterClockWiseSideOrientation = 1;
  36055. /**
  36056. * The dirty texture flag value
  36057. */
  36058. Material._TextureDirtyFlag = 1;
  36059. /**
  36060. * The dirty light flag value
  36061. */
  36062. Material._LightDirtyFlag = 2;
  36063. /**
  36064. * The dirty fresnel flag value
  36065. */
  36066. Material._FresnelDirtyFlag = 4;
  36067. /**
  36068. * The dirty attribute flag value
  36069. */
  36070. Material._AttributesDirtyFlag = 8;
  36071. /**
  36072. * The dirty misc flag value
  36073. */
  36074. Material._MiscDirtyFlag = 16;
  36075. __decorate([
  36076. BABYLON.serialize()
  36077. ], Material.prototype, "id", void 0);
  36078. __decorate([
  36079. BABYLON.serialize()
  36080. ], Material.prototype, "uniqueId", void 0);
  36081. __decorate([
  36082. BABYLON.serialize()
  36083. ], Material.prototype, "name", void 0);
  36084. __decorate([
  36085. BABYLON.serialize()
  36086. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36087. __decorate([
  36088. BABYLON.serialize()
  36089. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36090. __decorate([
  36091. BABYLON.serialize()
  36092. ], Material.prototype, "state", void 0);
  36093. __decorate([
  36094. BABYLON.serialize("alpha")
  36095. ], Material.prototype, "_alpha", void 0);
  36096. __decorate([
  36097. BABYLON.serialize("backFaceCulling")
  36098. ], Material.prototype, "_backFaceCulling", void 0);
  36099. __decorate([
  36100. BABYLON.serialize()
  36101. ], Material.prototype, "sideOrientation", void 0);
  36102. __decorate([
  36103. BABYLON.serialize("alphaMode")
  36104. ], Material.prototype, "_alphaMode", void 0);
  36105. __decorate([
  36106. BABYLON.serialize()
  36107. ], Material.prototype, "_needDepthPrePass", void 0);
  36108. __decorate([
  36109. BABYLON.serialize()
  36110. ], Material.prototype, "disableDepthWrite", void 0);
  36111. __decorate([
  36112. BABYLON.serialize()
  36113. ], Material.prototype, "forceDepthWrite", void 0);
  36114. __decorate([
  36115. BABYLON.serialize()
  36116. ], Material.prototype, "separateCullingPass", void 0);
  36117. __decorate([
  36118. BABYLON.serialize("fogEnabled")
  36119. ], Material.prototype, "_fogEnabled", void 0);
  36120. __decorate([
  36121. BABYLON.serialize()
  36122. ], Material.prototype, "pointSize", void 0);
  36123. __decorate([
  36124. BABYLON.serialize()
  36125. ], Material.prototype, "zOffset", void 0);
  36126. __decorate([
  36127. BABYLON.serialize()
  36128. ], Material.prototype, "wireframe", null);
  36129. __decorate([
  36130. BABYLON.serialize()
  36131. ], Material.prototype, "pointsCloud", null);
  36132. __decorate([
  36133. BABYLON.serialize()
  36134. ], Material.prototype, "fillMode", null);
  36135. return Material;
  36136. }());
  36137. BABYLON.Material = Material;
  36138. })(BABYLON || (BABYLON = {}));
  36139. //# sourceMappingURL=babylon.material.js.map
  36140. var BABYLON;
  36141. (function (BABYLON) {
  36142. var UniformBuffer = /** @class */ (function () {
  36143. /**
  36144. * Uniform buffer objects.
  36145. *
  36146. * Handles blocks of uniform on the GPU.
  36147. *
  36148. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36149. *
  36150. * For more information, please refer to :
  36151. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36152. */
  36153. function UniformBuffer(engine, data, dynamic) {
  36154. this._engine = engine;
  36155. this._noUBO = !engine.supportsUniformBuffers;
  36156. this._dynamic = dynamic;
  36157. this._data = data || [];
  36158. this._uniformLocations = {};
  36159. this._uniformSizes = {};
  36160. this._uniformLocationPointer = 0;
  36161. this._needSync = false;
  36162. if (this._noUBO) {
  36163. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36164. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36165. this.updateFloat = this._updateFloatForEffect;
  36166. this.updateFloat2 = this._updateFloat2ForEffect;
  36167. this.updateFloat3 = this._updateFloat3ForEffect;
  36168. this.updateFloat4 = this._updateFloat4ForEffect;
  36169. this.updateMatrix = this._updateMatrixForEffect;
  36170. this.updateVector3 = this._updateVector3ForEffect;
  36171. this.updateVector4 = this._updateVector4ForEffect;
  36172. this.updateColor3 = this._updateColor3ForEffect;
  36173. this.updateColor4 = this._updateColor4ForEffect;
  36174. }
  36175. else {
  36176. this._engine._uniformBuffers.push(this);
  36177. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36178. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36179. this.updateFloat = this._updateFloatForUniform;
  36180. this.updateFloat2 = this._updateFloat2ForUniform;
  36181. this.updateFloat3 = this._updateFloat3ForUniform;
  36182. this.updateFloat4 = this._updateFloat4ForUniform;
  36183. this.updateMatrix = this._updateMatrixForUniform;
  36184. this.updateVector3 = this._updateVector3ForUniform;
  36185. this.updateVector4 = this._updateVector4ForUniform;
  36186. this.updateColor3 = this._updateColor3ForUniform;
  36187. this.updateColor4 = this._updateColor4ForUniform;
  36188. }
  36189. }
  36190. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36191. // Properties
  36192. /**
  36193. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36194. * or just falling back on setUniformXXX calls.
  36195. */
  36196. get: function () {
  36197. return !this._noUBO;
  36198. },
  36199. enumerable: true,
  36200. configurable: true
  36201. });
  36202. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36203. /**
  36204. * Indicates if the WebGL underlying uniform buffer is in sync
  36205. * with the javascript cache data.
  36206. */
  36207. get: function () {
  36208. return !this._needSync;
  36209. },
  36210. enumerable: true,
  36211. configurable: true
  36212. });
  36213. /**
  36214. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36215. * Also, a dynamic UniformBuffer will disable cache verification and always
  36216. * update the underlying WebGL uniform buffer to the GPU.
  36217. */
  36218. UniformBuffer.prototype.isDynamic = function () {
  36219. return this._dynamic !== undefined;
  36220. };
  36221. /**
  36222. * The data cache on JS side.
  36223. */
  36224. UniformBuffer.prototype.getData = function () {
  36225. return this._bufferData;
  36226. };
  36227. /**
  36228. * The underlying WebGL Uniform buffer.
  36229. */
  36230. UniformBuffer.prototype.getBuffer = function () {
  36231. return this._buffer;
  36232. };
  36233. /**
  36234. * std140 layout specifies how to align data within an UBO structure.
  36235. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36236. * for specs.
  36237. */
  36238. UniformBuffer.prototype._fillAlignment = function (size) {
  36239. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36240. // and 4x4 matrices
  36241. // TODO : change if other types are used
  36242. var alignment;
  36243. if (size <= 2) {
  36244. alignment = size;
  36245. }
  36246. else {
  36247. alignment = 4;
  36248. }
  36249. if ((this._uniformLocationPointer % alignment) !== 0) {
  36250. var oldPointer = this._uniformLocationPointer;
  36251. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36252. var diff = this._uniformLocationPointer - oldPointer;
  36253. for (var i = 0; i < diff; i++) {
  36254. this._data.push(0);
  36255. }
  36256. }
  36257. };
  36258. /**
  36259. * Adds an uniform in the buffer.
  36260. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36261. * for the layout to be correct !
  36262. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36263. * @param {number|number[]} size Data size, or data directly.
  36264. */
  36265. UniformBuffer.prototype.addUniform = function (name, size) {
  36266. if (this._noUBO) {
  36267. return;
  36268. }
  36269. if (this._uniformLocations[name] !== undefined) {
  36270. // Already existing uniform
  36271. return;
  36272. }
  36273. // This function must be called in the order of the shader layout !
  36274. // size can be the size of the uniform, or data directly
  36275. var data;
  36276. if (size instanceof Array) {
  36277. data = size;
  36278. size = data.length;
  36279. }
  36280. else {
  36281. size = size;
  36282. data = [];
  36283. // Fill with zeros
  36284. for (var i = 0; i < size; i++) {
  36285. data.push(0);
  36286. }
  36287. }
  36288. this._fillAlignment(size);
  36289. this._uniformSizes[name] = size;
  36290. this._uniformLocations[name] = this._uniformLocationPointer;
  36291. this._uniformLocationPointer += size;
  36292. for (var i = 0; i < size; i++) {
  36293. this._data.push(data[i]);
  36294. }
  36295. this._needSync = true;
  36296. };
  36297. /**
  36298. * Wrapper for addUniform.
  36299. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36300. * @param {Matrix} mat A 4x4 matrix.
  36301. */
  36302. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36303. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36304. };
  36305. /**
  36306. * Wrapper for addUniform.
  36307. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36308. * @param {number} x
  36309. * @param {number} y
  36310. */
  36311. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36312. var temp = [x, y];
  36313. this.addUniform(name, temp);
  36314. };
  36315. /**
  36316. * Wrapper for addUniform.
  36317. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36318. * @param {number} x
  36319. * @param {number} y
  36320. * @param {number} z
  36321. */
  36322. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36323. var temp = [x, y, z];
  36324. this.addUniform(name, temp);
  36325. };
  36326. /**
  36327. * Wrapper for addUniform.
  36328. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36329. * @param {Color3} color
  36330. */
  36331. UniformBuffer.prototype.addColor3 = function (name, color) {
  36332. var temp = new Array();
  36333. color.toArray(temp);
  36334. this.addUniform(name, temp);
  36335. };
  36336. /**
  36337. * Wrapper for addUniform.
  36338. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36339. * @param {Color3} color
  36340. * @param {number} alpha
  36341. */
  36342. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36343. var temp = new Array();
  36344. color.toArray(temp);
  36345. temp.push(alpha);
  36346. this.addUniform(name, temp);
  36347. };
  36348. /**
  36349. * Wrapper for addUniform.
  36350. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36351. * @param {Vector3} vector
  36352. */
  36353. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36354. var temp = new Array();
  36355. vector.toArray(temp);
  36356. this.addUniform(name, temp);
  36357. };
  36358. /**
  36359. * Wrapper for addUniform.
  36360. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36361. */
  36362. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36363. this.addUniform(name, 12);
  36364. };
  36365. /**
  36366. * Wrapper for addUniform.
  36367. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36368. */
  36369. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36370. this.addUniform(name, 8);
  36371. };
  36372. /**
  36373. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36374. */
  36375. UniformBuffer.prototype.create = function () {
  36376. if (this._noUBO) {
  36377. return;
  36378. }
  36379. if (this._buffer) {
  36380. return; // nothing to do
  36381. }
  36382. // See spec, alignment must be filled as a vec4
  36383. this._fillAlignment(4);
  36384. this._bufferData = new Float32Array(this._data);
  36385. this._rebuild();
  36386. this._needSync = true;
  36387. };
  36388. UniformBuffer.prototype._rebuild = function () {
  36389. if (this._noUBO) {
  36390. return;
  36391. }
  36392. if (this._dynamic) {
  36393. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36394. }
  36395. else {
  36396. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36397. }
  36398. };
  36399. /**
  36400. * Updates the WebGL Uniform Buffer on the GPU.
  36401. * If the `dynamic` flag is set to true, no cache comparison is done.
  36402. * Otherwise, the buffer will be updated only if the cache differs.
  36403. */
  36404. UniformBuffer.prototype.update = function () {
  36405. if (!this._buffer) {
  36406. this.create();
  36407. return;
  36408. }
  36409. if (!this._dynamic && !this._needSync) {
  36410. return;
  36411. }
  36412. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36413. this._needSync = false;
  36414. };
  36415. /**
  36416. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36417. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36418. * @param {number[]|Float32Array} data Flattened data
  36419. * @param {number} size Size of the data.
  36420. */
  36421. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36422. var location = this._uniformLocations[uniformName];
  36423. if (location === undefined) {
  36424. if (this._buffer) {
  36425. // Cannot add an uniform if the buffer is already created
  36426. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36427. return;
  36428. }
  36429. this.addUniform(uniformName, size);
  36430. location = this._uniformLocations[uniformName];
  36431. }
  36432. if (!this._buffer) {
  36433. this.create();
  36434. }
  36435. if (!this._dynamic) {
  36436. // Cache for static uniform buffers
  36437. var changed = false;
  36438. for (var i = 0; i < size; i++) {
  36439. if (this._bufferData[location + i] !== data[i]) {
  36440. changed = true;
  36441. this._bufferData[location + i] = data[i];
  36442. }
  36443. }
  36444. this._needSync = this._needSync || changed;
  36445. }
  36446. else {
  36447. // No cache for dynamic
  36448. for (var i = 0; i < size; i++) {
  36449. this._bufferData[location + i] = data[i];
  36450. }
  36451. }
  36452. };
  36453. // Update methods
  36454. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36455. // To match std140, matrix must be realigned
  36456. for (var i = 0; i < 3; i++) {
  36457. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36458. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36459. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36460. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36461. }
  36462. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36463. };
  36464. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36465. this._currentEffect.setMatrix3x3(name, matrix);
  36466. };
  36467. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36468. this._currentEffect.setMatrix2x2(name, matrix);
  36469. };
  36470. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36471. // To match std140, matrix must be realigned
  36472. for (var i = 0; i < 2; i++) {
  36473. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36474. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36475. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36476. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36477. }
  36478. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36479. };
  36480. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36481. this._currentEffect.setFloat(name, x);
  36482. };
  36483. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36484. UniformBuffer._tempBuffer[0] = x;
  36485. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36486. };
  36487. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36488. if (suffix === void 0) { suffix = ""; }
  36489. this._currentEffect.setFloat2(name + suffix, x, y);
  36490. };
  36491. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36492. if (suffix === void 0) { suffix = ""; }
  36493. UniformBuffer._tempBuffer[0] = x;
  36494. UniformBuffer._tempBuffer[1] = y;
  36495. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36496. };
  36497. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36498. if (suffix === void 0) { suffix = ""; }
  36499. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36500. };
  36501. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36502. if (suffix === void 0) { suffix = ""; }
  36503. UniformBuffer._tempBuffer[0] = x;
  36504. UniformBuffer._tempBuffer[1] = y;
  36505. UniformBuffer._tempBuffer[2] = z;
  36506. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36507. };
  36508. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36509. if (suffix === void 0) { suffix = ""; }
  36510. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36511. };
  36512. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36513. if (suffix === void 0) { suffix = ""; }
  36514. UniformBuffer._tempBuffer[0] = x;
  36515. UniformBuffer._tempBuffer[1] = y;
  36516. UniformBuffer._tempBuffer[2] = z;
  36517. UniformBuffer._tempBuffer[3] = w;
  36518. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36519. };
  36520. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36521. this._currentEffect.setMatrix(name, mat);
  36522. };
  36523. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36524. this.updateUniform(name, mat.toArray(), 16);
  36525. };
  36526. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36527. this._currentEffect.setVector3(name, vector);
  36528. };
  36529. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36530. vector.toArray(UniformBuffer._tempBuffer);
  36531. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36532. };
  36533. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36534. this._currentEffect.setVector4(name, vector);
  36535. };
  36536. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36537. vector.toArray(UniformBuffer._tempBuffer);
  36538. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36539. };
  36540. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36541. if (suffix === void 0) { suffix = ""; }
  36542. this._currentEffect.setColor3(name + suffix, color);
  36543. };
  36544. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36545. if (suffix === void 0) { suffix = ""; }
  36546. color.toArray(UniformBuffer._tempBuffer);
  36547. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36548. };
  36549. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36550. if (suffix === void 0) { suffix = ""; }
  36551. this._currentEffect.setColor4(name + suffix, color, alpha);
  36552. };
  36553. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36554. if (suffix === void 0) { suffix = ""; }
  36555. color.toArray(UniformBuffer._tempBuffer);
  36556. UniformBuffer._tempBuffer[3] = alpha;
  36557. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36558. };
  36559. /**
  36560. * Sets a sampler uniform on the effect.
  36561. * @param {string} name Name of the sampler.
  36562. * @param {Texture} texture
  36563. */
  36564. UniformBuffer.prototype.setTexture = function (name, texture) {
  36565. this._currentEffect.setTexture(name, texture);
  36566. };
  36567. /**
  36568. * Directly updates the value of the uniform in the cache AND on the GPU.
  36569. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36570. * @param {number[]|Float32Array} data Flattened data
  36571. */
  36572. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36573. this.updateUniform(uniformName, data, data.length);
  36574. this.update();
  36575. };
  36576. /**
  36577. * Binds this uniform buffer to an effect.
  36578. * @param {Effect} effect
  36579. * @param {string} name Name of the uniform block in the shader.
  36580. */
  36581. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36582. this._currentEffect = effect;
  36583. if (this._noUBO || !this._buffer) {
  36584. return;
  36585. }
  36586. effect.bindUniformBuffer(this._buffer, name);
  36587. };
  36588. /**
  36589. * Disposes the uniform buffer.
  36590. */
  36591. UniformBuffer.prototype.dispose = function () {
  36592. if (this._noUBO) {
  36593. return;
  36594. }
  36595. var index = this._engine._uniformBuffers.indexOf(this);
  36596. if (index !== -1) {
  36597. this._engine._uniformBuffers.splice(index, 1);
  36598. }
  36599. if (!this._buffer) {
  36600. return;
  36601. }
  36602. if (this._engine._releaseBuffer(this._buffer)) {
  36603. this._buffer = null;
  36604. }
  36605. };
  36606. // Pool for avoiding memory leaks
  36607. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36608. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36609. return UniformBuffer;
  36610. }());
  36611. BABYLON.UniformBuffer = UniformBuffer;
  36612. })(BABYLON || (BABYLON = {}));
  36613. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36614. var BABYLON;
  36615. (function (BABYLON) {
  36616. /**
  36617. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36618. */
  36619. var VertexData = /** @class */ (function () {
  36620. function VertexData() {
  36621. }
  36622. /**
  36623. * Uses the passed data array to set the set the values for the specified kind of data
  36624. * @param data a linear array of floating numbers
  36625. * @param kind the type of data that is being set, eg positions, colors etc
  36626. */
  36627. VertexData.prototype.set = function (data, kind) {
  36628. switch (kind) {
  36629. case BABYLON.VertexBuffer.PositionKind:
  36630. this.positions = data;
  36631. break;
  36632. case BABYLON.VertexBuffer.NormalKind:
  36633. this.normals = data;
  36634. break;
  36635. case BABYLON.VertexBuffer.TangentKind:
  36636. this.tangents = data;
  36637. break;
  36638. case BABYLON.VertexBuffer.UVKind:
  36639. this.uvs = data;
  36640. break;
  36641. case BABYLON.VertexBuffer.UV2Kind:
  36642. this.uvs2 = data;
  36643. break;
  36644. case BABYLON.VertexBuffer.UV3Kind:
  36645. this.uvs3 = data;
  36646. break;
  36647. case BABYLON.VertexBuffer.UV4Kind:
  36648. this.uvs4 = data;
  36649. break;
  36650. case BABYLON.VertexBuffer.UV5Kind:
  36651. this.uvs5 = data;
  36652. break;
  36653. case BABYLON.VertexBuffer.UV6Kind:
  36654. this.uvs6 = data;
  36655. break;
  36656. case BABYLON.VertexBuffer.ColorKind:
  36657. this.colors = data;
  36658. break;
  36659. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36660. this.matricesIndices = data;
  36661. break;
  36662. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36663. this.matricesWeights = data;
  36664. break;
  36665. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36666. this.matricesIndicesExtra = data;
  36667. break;
  36668. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36669. this.matricesWeightsExtra = data;
  36670. break;
  36671. }
  36672. };
  36673. /**
  36674. * Associates the vertexData to the passed Mesh.
  36675. * Sets it as updatable or not (default `false`)
  36676. * @param mesh the mesh the vertexData is applied to
  36677. * @param updatable when used and having the value true allows new data to update the vertexData
  36678. * @returns the VertexData
  36679. */
  36680. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36681. this._applyTo(mesh, updatable);
  36682. return this;
  36683. };
  36684. /**
  36685. * Associates the vertexData to the passed Geometry.
  36686. * Sets it as updatable or not (default `false`)
  36687. * @param geometry the geometry the vertexData is applied to
  36688. * @param updatable when used and having the value true allows new data to update the vertexData
  36689. * @returns VertexData
  36690. */
  36691. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36692. this._applyTo(geometry, updatable);
  36693. return this;
  36694. };
  36695. /**
  36696. * Updates the associated mesh
  36697. * @param mesh the mesh to be updated
  36698. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36699. * @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
  36700. * @returns VertexData
  36701. */
  36702. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36703. this._update(mesh);
  36704. return this;
  36705. };
  36706. /**
  36707. * Updates the associated geometry
  36708. * @param geometry the geometry to be updated
  36709. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36710. * @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
  36711. * @returns VertexData.
  36712. */
  36713. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36714. this._update(geometry);
  36715. return this;
  36716. };
  36717. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36718. if (updatable === void 0) { updatable = false; }
  36719. if (this.positions) {
  36720. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36721. }
  36722. if (this.normals) {
  36723. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36724. }
  36725. if (this.tangents) {
  36726. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36727. }
  36728. if (this.uvs) {
  36729. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36730. }
  36731. if (this.uvs2) {
  36732. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36733. }
  36734. if (this.uvs3) {
  36735. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36736. }
  36737. if (this.uvs4) {
  36738. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36739. }
  36740. if (this.uvs5) {
  36741. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36742. }
  36743. if (this.uvs6) {
  36744. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36745. }
  36746. if (this.colors) {
  36747. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36748. }
  36749. if (this.matricesIndices) {
  36750. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36751. }
  36752. if (this.matricesWeights) {
  36753. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36754. }
  36755. if (this.matricesIndicesExtra) {
  36756. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36757. }
  36758. if (this.matricesWeightsExtra) {
  36759. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36760. }
  36761. if (this.indices) {
  36762. meshOrGeometry.setIndices(this.indices, null, updatable);
  36763. }
  36764. else {
  36765. meshOrGeometry.setIndices([], null);
  36766. }
  36767. return this;
  36768. };
  36769. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36770. if (this.positions) {
  36771. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36772. }
  36773. if (this.normals) {
  36774. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36775. }
  36776. if (this.tangents) {
  36777. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36778. }
  36779. if (this.uvs) {
  36780. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36781. }
  36782. if (this.uvs2) {
  36783. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36784. }
  36785. if (this.uvs3) {
  36786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36787. }
  36788. if (this.uvs4) {
  36789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36790. }
  36791. if (this.uvs5) {
  36792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36793. }
  36794. if (this.uvs6) {
  36795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36796. }
  36797. if (this.colors) {
  36798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36799. }
  36800. if (this.matricesIndices) {
  36801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36802. }
  36803. if (this.matricesWeights) {
  36804. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36805. }
  36806. if (this.matricesIndicesExtra) {
  36807. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36808. }
  36809. if (this.matricesWeightsExtra) {
  36810. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36811. }
  36812. if (this.indices) {
  36813. meshOrGeometry.setIndices(this.indices, null);
  36814. }
  36815. return this;
  36816. };
  36817. /**
  36818. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36819. * @param matrix the transforming matrix
  36820. * @returns the VertexData
  36821. */
  36822. VertexData.prototype.transform = function (matrix) {
  36823. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36824. var transformed = BABYLON.Vector3.Zero();
  36825. var index;
  36826. if (this.positions) {
  36827. var position = BABYLON.Vector3.Zero();
  36828. for (index = 0; index < this.positions.length; index += 3) {
  36829. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36830. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36831. this.positions[index] = transformed.x;
  36832. this.positions[index + 1] = transformed.y;
  36833. this.positions[index + 2] = transformed.z;
  36834. }
  36835. }
  36836. if (this.normals) {
  36837. var normal = BABYLON.Vector3.Zero();
  36838. for (index = 0; index < this.normals.length; index += 3) {
  36839. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36840. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36841. this.normals[index] = transformed.x;
  36842. this.normals[index + 1] = transformed.y;
  36843. this.normals[index + 2] = transformed.z;
  36844. }
  36845. }
  36846. if (this.tangents) {
  36847. var tangent = BABYLON.Vector4.Zero();
  36848. var tangentTransformed = BABYLON.Vector4.Zero();
  36849. for (index = 0; index < this.tangents.length; index += 4) {
  36850. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36851. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36852. this.tangents[index] = tangentTransformed.x;
  36853. this.tangents[index + 1] = tangentTransformed.y;
  36854. this.tangents[index + 2] = tangentTransformed.z;
  36855. this.tangents[index + 3] = tangentTransformed.w;
  36856. }
  36857. }
  36858. if (flip && this.indices) {
  36859. for (index = 0; index < this.indices.length; index += 3) {
  36860. var tmp = this.indices[index + 1];
  36861. this.indices[index + 1] = this.indices[index + 2];
  36862. this.indices[index + 2] = tmp;
  36863. }
  36864. }
  36865. return this;
  36866. };
  36867. /**
  36868. * Merges the passed VertexData into the current one
  36869. * @param other the VertexData to be merged into the current one
  36870. * @returns the modified VertexData
  36871. */
  36872. VertexData.prototype.merge = function (other) {
  36873. this._validate();
  36874. other._validate();
  36875. if (!this.normals !== !other.normals ||
  36876. !this.tangents !== !other.tangents ||
  36877. !this.uvs !== !other.uvs ||
  36878. !this.uvs2 !== !other.uvs2 ||
  36879. !this.uvs3 !== !other.uvs3 ||
  36880. !this.uvs4 !== !other.uvs4 ||
  36881. !this.uvs5 !== !other.uvs5 ||
  36882. !this.uvs6 !== !other.uvs6 ||
  36883. !this.colors !== !other.colors ||
  36884. !this.matricesIndices !== !other.matricesIndices ||
  36885. !this.matricesWeights !== !other.matricesWeights ||
  36886. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36887. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36888. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36889. }
  36890. if (other.indices) {
  36891. if (!this.indices) {
  36892. this.indices = [];
  36893. }
  36894. var offset = this.positions ? this.positions.length / 3 : 0;
  36895. for (var index = 0; index < other.indices.length; index++) {
  36896. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36897. this.indices.push(other.indices[index] + offset);
  36898. }
  36899. }
  36900. this.positions = this._mergeElement(this.positions, other.positions);
  36901. this.normals = this._mergeElement(this.normals, other.normals);
  36902. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36903. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36904. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36905. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36906. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36907. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36908. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36909. this.colors = this._mergeElement(this.colors, other.colors);
  36910. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36911. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36912. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36913. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36914. return this;
  36915. };
  36916. VertexData.prototype._mergeElement = function (source, other) {
  36917. if (!source) {
  36918. return other;
  36919. }
  36920. if (!other) {
  36921. return source;
  36922. }
  36923. var len = other.length + source.length;
  36924. var isSrcTypedArray = source instanceof Float32Array;
  36925. var isOthTypedArray = other instanceof Float32Array;
  36926. // use non-loop method when the source is Float32Array
  36927. if (isSrcTypedArray) {
  36928. var ret32 = new Float32Array(len);
  36929. ret32.set(source);
  36930. ret32.set(other, source.length);
  36931. return ret32;
  36932. // source is number[], when other is also use concat
  36933. }
  36934. else if (!isOthTypedArray) {
  36935. return source.concat(other);
  36936. // source is a number[], but other is a Float32Array, loop required
  36937. }
  36938. else {
  36939. var ret = source.slice(0); // copy source to a separate array
  36940. for (var i = 0, len = other.length; i < len; i++) {
  36941. ret.push(other[i]);
  36942. }
  36943. return ret;
  36944. }
  36945. };
  36946. VertexData.prototype._validate = function () {
  36947. if (!this.positions) {
  36948. throw new Error("Positions are required");
  36949. }
  36950. var getElementCount = function (kind, values) {
  36951. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36952. if ((values.length % stride) !== 0) {
  36953. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36954. }
  36955. return values.length / stride;
  36956. };
  36957. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36958. var validateElementCount = function (kind, values) {
  36959. var elementCount = getElementCount(kind, values);
  36960. if (elementCount !== positionsElementCount) {
  36961. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36962. }
  36963. };
  36964. if (this.normals)
  36965. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36966. if (this.tangents)
  36967. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36968. if (this.uvs)
  36969. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36970. if (this.uvs2)
  36971. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36972. if (this.uvs3)
  36973. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36974. if (this.uvs4)
  36975. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36976. if (this.uvs5)
  36977. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36978. if (this.uvs6)
  36979. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36980. if (this.colors)
  36981. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36982. if (this.matricesIndices)
  36983. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36984. if (this.matricesWeights)
  36985. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36986. if (this.matricesIndicesExtra)
  36987. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36988. if (this.matricesWeightsExtra)
  36989. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36990. };
  36991. /**
  36992. * Serializes the VertexData
  36993. * @returns a serialized object
  36994. */
  36995. VertexData.prototype.serialize = function () {
  36996. var serializationObject = this.serialize();
  36997. if (this.positions) {
  36998. serializationObject.positions = this.positions;
  36999. }
  37000. if (this.normals) {
  37001. serializationObject.normals = this.normals;
  37002. }
  37003. if (this.tangents) {
  37004. serializationObject.tangents = this.tangents;
  37005. }
  37006. if (this.uvs) {
  37007. serializationObject.uvs = this.uvs;
  37008. }
  37009. if (this.uvs2) {
  37010. serializationObject.uvs2 = this.uvs2;
  37011. }
  37012. if (this.uvs3) {
  37013. serializationObject.uvs3 = this.uvs3;
  37014. }
  37015. if (this.uvs4) {
  37016. serializationObject.uvs4 = this.uvs4;
  37017. }
  37018. if (this.uvs5) {
  37019. serializationObject.uvs5 = this.uvs5;
  37020. }
  37021. if (this.uvs6) {
  37022. serializationObject.uvs6 = this.uvs6;
  37023. }
  37024. if (this.colors) {
  37025. serializationObject.colors = this.colors;
  37026. }
  37027. if (this.matricesIndices) {
  37028. serializationObject.matricesIndices = this.matricesIndices;
  37029. serializationObject.matricesIndices._isExpanded = true;
  37030. }
  37031. if (this.matricesWeights) {
  37032. serializationObject.matricesWeights = this.matricesWeights;
  37033. }
  37034. if (this.matricesIndicesExtra) {
  37035. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37036. serializationObject.matricesIndicesExtra._isExpanded = true;
  37037. }
  37038. if (this.matricesWeightsExtra) {
  37039. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37040. }
  37041. serializationObject.indices = this.indices;
  37042. return serializationObject;
  37043. };
  37044. // Statics
  37045. /**
  37046. * Extracts the vertexData from a mesh
  37047. * @param mesh the mesh from which to extract the VertexData
  37048. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37049. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37050. * @returns the object VertexData associated to the passed mesh
  37051. */
  37052. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37053. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37054. };
  37055. /**
  37056. * Extracts the vertexData from the geometry
  37057. * @param geometry the geometry from which to extract the VertexData
  37058. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37059. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37060. * @returns the object VertexData associated to the passed mesh
  37061. */
  37062. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37063. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37064. };
  37065. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37066. var result = new VertexData();
  37067. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37068. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37069. }
  37070. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37071. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37072. }
  37073. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37074. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37075. }
  37076. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37077. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37078. }
  37079. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37080. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37081. }
  37082. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37083. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37084. }
  37085. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37086. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37087. }
  37088. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37089. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37090. }
  37091. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37092. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37093. }
  37094. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37095. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37096. }
  37097. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37098. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37099. }
  37100. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37101. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37102. }
  37103. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37104. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37105. }
  37106. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37107. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37108. }
  37109. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37110. return result;
  37111. };
  37112. /**
  37113. * Creates the VertexData for a Ribbon
  37114. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37115. * * pathArray array of paths, each of which an array of successive Vector3
  37116. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37117. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37118. * * 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
  37119. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37120. * * 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)
  37121. * * 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)
  37122. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37123. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37124. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37125. * @returns the VertexData of the ribbon
  37126. */
  37127. VertexData.CreateRibbon = function (options) {
  37128. var pathArray = options.pathArray;
  37129. var closeArray = options.closeArray || false;
  37130. var closePath = options.closePath || false;
  37131. var invertUV = options.invertUV || false;
  37132. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37133. var offset = options.offset || defaultOffset;
  37134. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37135. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37136. var customUV = options.uvs;
  37137. var customColors = options.colors;
  37138. var positions = [];
  37139. var indices = [];
  37140. var normals = [];
  37141. var uvs = [];
  37142. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37143. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37144. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37145. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37146. var minlg; // minimal length among all paths from pathArray
  37147. var lg = []; // array of path lengths : nb of vertex per path
  37148. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37149. var p; // path iterator
  37150. var i; // point iterator
  37151. var j; // point iterator
  37152. // if single path in pathArray
  37153. if (pathArray.length < 2) {
  37154. var ar1 = [];
  37155. var ar2 = [];
  37156. for (i = 0; i < pathArray[0].length - offset; i++) {
  37157. ar1.push(pathArray[0][i]);
  37158. ar2.push(pathArray[0][i + offset]);
  37159. }
  37160. pathArray = [ar1, ar2];
  37161. }
  37162. // positions and horizontal distances (u)
  37163. var idc = 0;
  37164. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37165. var path;
  37166. var l;
  37167. minlg = pathArray[0].length;
  37168. var vectlg;
  37169. var dist;
  37170. for (p = 0; p < pathArray.length; p++) {
  37171. uTotalDistance[p] = 0;
  37172. us[p] = [0];
  37173. path = pathArray[p];
  37174. l = path.length;
  37175. minlg = (minlg < l) ? minlg : l;
  37176. j = 0;
  37177. while (j < l) {
  37178. positions.push(path[j].x, path[j].y, path[j].z);
  37179. if (j > 0) {
  37180. vectlg = path[j].subtract(path[j - 1]).length();
  37181. dist = vectlg + uTotalDistance[p];
  37182. us[p].push(dist);
  37183. uTotalDistance[p] = dist;
  37184. }
  37185. j++;
  37186. }
  37187. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37188. j--;
  37189. positions.push(path[0].x, path[0].y, path[0].z);
  37190. vectlg = path[j].subtract(path[0]).length();
  37191. dist = vectlg + uTotalDistance[p];
  37192. us[p].push(dist);
  37193. uTotalDistance[p] = dist;
  37194. }
  37195. lg[p] = l + closePathCorr;
  37196. idx[p] = idc;
  37197. idc += (l + closePathCorr);
  37198. }
  37199. // vertical distances (v)
  37200. var path1;
  37201. var path2;
  37202. var vertex1 = null;
  37203. var vertex2 = null;
  37204. for (i = 0; i < minlg + closePathCorr; i++) {
  37205. vTotalDistance[i] = 0;
  37206. vs[i] = [0];
  37207. for (p = 0; p < pathArray.length - 1; p++) {
  37208. path1 = pathArray[p];
  37209. path2 = pathArray[p + 1];
  37210. if (i === minlg) { // closePath
  37211. vertex1 = path1[0];
  37212. vertex2 = path2[0];
  37213. }
  37214. else {
  37215. vertex1 = path1[i];
  37216. vertex2 = path2[i];
  37217. }
  37218. vectlg = vertex2.subtract(vertex1).length();
  37219. dist = vectlg + vTotalDistance[i];
  37220. vs[i].push(dist);
  37221. vTotalDistance[i] = dist;
  37222. }
  37223. if (closeArray && vertex2 && vertex1) {
  37224. path1 = pathArray[p];
  37225. path2 = pathArray[0];
  37226. if (i === minlg) { // closePath
  37227. vertex2 = path2[0];
  37228. }
  37229. vectlg = vertex2.subtract(vertex1).length();
  37230. dist = vectlg + vTotalDistance[i];
  37231. vTotalDistance[i] = dist;
  37232. }
  37233. }
  37234. // uvs
  37235. var u;
  37236. var v;
  37237. if (customUV) {
  37238. for (p = 0; p < customUV.length; p++) {
  37239. uvs.push(customUV[p].x, customUV[p].y);
  37240. }
  37241. }
  37242. else {
  37243. for (p = 0; p < pathArray.length; p++) {
  37244. for (i = 0; i < minlg + closePathCorr; i++) {
  37245. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37246. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37247. if (invertUV) {
  37248. uvs.push(v, u);
  37249. }
  37250. else {
  37251. uvs.push(u, v);
  37252. }
  37253. }
  37254. }
  37255. }
  37256. // indices
  37257. p = 0; // path index
  37258. var pi = 0; // positions array index
  37259. var l1 = lg[p] - 1; // path1 length
  37260. var l2 = lg[p + 1] - 1; // path2 length
  37261. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37262. var shft = idx[1] - idx[0]; // shift
  37263. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37264. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37265. // 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
  37266. indices.push(pi, pi + shft, pi + 1);
  37267. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37268. pi += 1;
  37269. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37270. p++;
  37271. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37272. shft = idx[0] - idx[p];
  37273. l1 = lg[p] - 1;
  37274. l2 = lg[0] - 1;
  37275. }
  37276. else {
  37277. shft = idx[p + 1] - idx[p];
  37278. l1 = lg[p] - 1;
  37279. l2 = lg[p + 1] - 1;
  37280. }
  37281. pi = idx[p];
  37282. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37283. }
  37284. }
  37285. // normals
  37286. VertexData.ComputeNormals(positions, indices, normals);
  37287. if (closePath) { // update both the first and last vertex normals to their average value
  37288. var indexFirst = 0;
  37289. var indexLast = 0;
  37290. for (p = 0; p < pathArray.length; p++) {
  37291. indexFirst = idx[p] * 3;
  37292. if (p + 1 < pathArray.length) {
  37293. indexLast = (idx[p + 1] - 1) * 3;
  37294. }
  37295. else {
  37296. indexLast = normals.length - 3;
  37297. }
  37298. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37299. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37300. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37301. normals[indexLast] = normals[indexFirst];
  37302. normals[indexLast + 1] = normals[indexFirst + 1];
  37303. normals[indexLast + 2] = normals[indexFirst + 2];
  37304. }
  37305. }
  37306. // sides
  37307. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37308. // Colors
  37309. var colors = null;
  37310. if (customColors) {
  37311. colors = new Float32Array(customColors.length * 4);
  37312. for (var c = 0; c < customColors.length; c++) {
  37313. colors[c * 4] = customColors[c].r;
  37314. colors[c * 4 + 1] = customColors[c].g;
  37315. colors[c * 4 + 2] = customColors[c].b;
  37316. colors[c * 4 + 3] = customColors[c].a;
  37317. }
  37318. }
  37319. // Result
  37320. var vertexData = new VertexData();
  37321. var positions32 = new Float32Array(positions);
  37322. var normals32 = new Float32Array(normals);
  37323. var uvs32 = new Float32Array(uvs);
  37324. vertexData.indices = indices;
  37325. vertexData.positions = positions32;
  37326. vertexData.normals = normals32;
  37327. vertexData.uvs = uvs32;
  37328. if (colors) {
  37329. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37330. }
  37331. if (closePath) {
  37332. vertexData._idx = idx;
  37333. }
  37334. return vertexData;
  37335. };
  37336. /**
  37337. * Creates the VertexData for a box
  37338. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37339. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37340. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37341. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37342. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37343. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37344. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37345. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37346. * * 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)
  37347. * * 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)
  37348. * @returns the VertexData of the box
  37349. */
  37350. VertexData.CreateBox = function (options) {
  37351. var normalsSource = [
  37352. new BABYLON.Vector3(0, 0, 1),
  37353. new BABYLON.Vector3(0, 0, -1),
  37354. new BABYLON.Vector3(1, 0, 0),
  37355. new BABYLON.Vector3(-1, 0, 0),
  37356. new BABYLON.Vector3(0, 1, 0),
  37357. new BABYLON.Vector3(0, -1, 0)
  37358. ];
  37359. var indices = [];
  37360. var positions = [];
  37361. var normals = [];
  37362. var uvs = [];
  37363. var width = options.width || options.size || 1;
  37364. var height = options.height || options.size || 1;
  37365. var depth = options.depth || options.size || 1;
  37366. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37367. var faceUV = options.faceUV || new Array(6);
  37368. var faceColors = options.faceColors;
  37369. var colors = [];
  37370. // default face colors and UV if undefined
  37371. for (var f = 0; f < 6; f++) {
  37372. if (faceUV[f] === undefined) {
  37373. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37374. }
  37375. if (faceColors && faceColors[f] === undefined) {
  37376. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37377. }
  37378. }
  37379. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37380. // Create each face in turn.
  37381. for (var index = 0; index < normalsSource.length; index++) {
  37382. var normal = normalsSource[index];
  37383. // Get two vectors perpendicular to the face normal and to each other.
  37384. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37385. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37386. // Six indices (two triangles) per face.
  37387. var verticesLength = positions.length / 3;
  37388. indices.push(verticesLength);
  37389. indices.push(verticesLength + 1);
  37390. indices.push(verticesLength + 2);
  37391. indices.push(verticesLength);
  37392. indices.push(verticesLength + 2);
  37393. indices.push(verticesLength + 3);
  37394. // Four vertices per face.
  37395. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37396. positions.push(vertex.x, vertex.y, vertex.z);
  37397. normals.push(normal.x, normal.y, normal.z);
  37398. uvs.push(faceUV[index].z, faceUV[index].w);
  37399. if (faceColors) {
  37400. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37401. }
  37402. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37403. positions.push(vertex.x, vertex.y, vertex.z);
  37404. normals.push(normal.x, normal.y, normal.z);
  37405. uvs.push(faceUV[index].x, faceUV[index].w);
  37406. if (faceColors) {
  37407. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37408. }
  37409. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37410. positions.push(vertex.x, vertex.y, vertex.z);
  37411. normals.push(normal.x, normal.y, normal.z);
  37412. uvs.push(faceUV[index].x, faceUV[index].y);
  37413. if (faceColors) {
  37414. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37415. }
  37416. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37417. positions.push(vertex.x, vertex.y, vertex.z);
  37418. normals.push(normal.x, normal.y, normal.z);
  37419. uvs.push(faceUV[index].z, faceUV[index].y);
  37420. if (faceColors) {
  37421. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37422. }
  37423. }
  37424. // sides
  37425. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37426. // Result
  37427. var vertexData = new VertexData();
  37428. vertexData.indices = indices;
  37429. vertexData.positions = positions;
  37430. vertexData.normals = normals;
  37431. vertexData.uvs = uvs;
  37432. if (faceColors) {
  37433. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37434. vertexData.colors = totalColors;
  37435. }
  37436. return vertexData;
  37437. };
  37438. /**
  37439. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37440. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37441. * * segments sets the number of horizontal strips optional, default 32
  37442. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37443. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37444. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37445. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37446. * * 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
  37447. * * 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
  37448. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37449. * * 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)
  37450. * * 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)
  37451. * @returns the VertexData of the ellipsoid
  37452. */
  37453. VertexData.CreateSphere = function (options) {
  37454. var segments = options.segments || 32;
  37455. var diameterX = options.diameterX || options.diameter || 1;
  37456. var diameterY = options.diameterY || options.diameter || 1;
  37457. var diameterZ = options.diameterZ || options.diameter || 1;
  37458. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37459. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37460. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37461. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37462. var totalZRotationSteps = 2 + segments;
  37463. var totalYRotationSteps = 2 * totalZRotationSteps;
  37464. var indices = [];
  37465. var positions = [];
  37466. var normals = [];
  37467. var uvs = [];
  37468. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37469. var normalizedZ = zRotationStep / totalZRotationSteps;
  37470. var angleZ = normalizedZ * Math.PI * slice;
  37471. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37472. var normalizedY = yRotationStep / totalYRotationSteps;
  37473. var angleY = normalizedY * Math.PI * 2 * arc;
  37474. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37475. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37476. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37477. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37478. var vertex = complete.multiply(radius);
  37479. var normal = complete.divide(radius).normalize();
  37480. positions.push(vertex.x, vertex.y, vertex.z);
  37481. normals.push(normal.x, normal.y, normal.z);
  37482. uvs.push(normalizedY, normalizedZ);
  37483. }
  37484. if (zRotationStep > 0) {
  37485. var verticesCount = positions.length / 3;
  37486. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37487. indices.push((firstIndex));
  37488. indices.push((firstIndex + 1));
  37489. indices.push(firstIndex + totalYRotationSteps + 1);
  37490. indices.push((firstIndex + totalYRotationSteps + 1));
  37491. indices.push((firstIndex + 1));
  37492. indices.push((firstIndex + totalYRotationSteps + 2));
  37493. }
  37494. }
  37495. }
  37496. // Sides
  37497. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37498. // Result
  37499. var vertexData = new VertexData();
  37500. vertexData.indices = indices;
  37501. vertexData.positions = positions;
  37502. vertexData.normals = normals;
  37503. vertexData.uvs = uvs;
  37504. return vertexData;
  37505. };
  37506. /**
  37507. * Creates the VertexData for a cylinder, cone or prism
  37508. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37509. * * height sets the height (y direction) of the cylinder, optional, default 2
  37510. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37511. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37512. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37513. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37514. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37515. * * 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
  37516. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37517. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37518. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37519. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37520. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37521. * * 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)
  37522. * * 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)
  37523. * @returns the VertexData of the cylinder, cone or prism
  37524. */
  37525. VertexData.CreateCylinder = function (options) {
  37526. var height = options.height || 2;
  37527. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37528. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37529. var tessellation = options.tessellation || 24;
  37530. var subdivisions = options.subdivisions || 1;
  37531. var hasRings = options.hasRings ? true : false;
  37532. var enclose = options.enclose ? true : false;
  37533. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37534. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37535. var faceUV = options.faceUV || new Array(3);
  37536. var faceColors = options.faceColors;
  37537. // default face colors and UV if undefined
  37538. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37539. var ringNb = (hasRings) ? subdivisions : 1;
  37540. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37541. var f;
  37542. for (f = 0; f < surfaceNb; f++) {
  37543. if (faceColors && faceColors[f] === undefined) {
  37544. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37545. }
  37546. }
  37547. for (f = 0; f < surfaceNb; f++) {
  37548. if (faceUV && faceUV[f] === undefined) {
  37549. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37550. }
  37551. }
  37552. var indices = new Array();
  37553. var positions = new Array();
  37554. var normals = new Array();
  37555. var uvs = new Array();
  37556. var colors = new Array();
  37557. var angle_step = Math.PI * 2 * arc / tessellation;
  37558. var angle;
  37559. var h;
  37560. var radius;
  37561. var tan = (diameterBottom - diameterTop) / 2 / height;
  37562. var ringVertex = BABYLON.Vector3.Zero();
  37563. var ringNormal = BABYLON.Vector3.Zero();
  37564. var ringFirstVertex = BABYLON.Vector3.Zero();
  37565. var ringFirstNormal = BABYLON.Vector3.Zero();
  37566. var quadNormal = BABYLON.Vector3.Zero();
  37567. var Y = BABYLON.Axis.Y;
  37568. // positions, normals, uvs
  37569. var i;
  37570. var j;
  37571. var r;
  37572. var ringIdx = 1;
  37573. var s = 1; // surface index
  37574. var cs = 0;
  37575. var v = 0;
  37576. for (i = 0; i <= subdivisions; i++) {
  37577. h = i / subdivisions;
  37578. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37579. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37580. for (r = 0; r < ringIdx; r++) {
  37581. if (hasRings) {
  37582. s += r;
  37583. }
  37584. if (enclose) {
  37585. s += 2 * r;
  37586. }
  37587. for (j = 0; j <= tessellation; j++) {
  37588. angle = j * angle_step;
  37589. // position
  37590. ringVertex.x = Math.cos(-angle) * radius;
  37591. ringVertex.y = -height / 2 + h * height;
  37592. ringVertex.z = Math.sin(-angle) * radius;
  37593. // normal
  37594. if (diameterTop === 0 && i === subdivisions) {
  37595. // if no top cap, reuse former normals
  37596. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37597. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37598. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37599. }
  37600. else {
  37601. ringNormal.x = ringVertex.x;
  37602. ringNormal.z = ringVertex.z;
  37603. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37604. ringNormal.normalize();
  37605. }
  37606. // keep first ring vertex values for enclose
  37607. if (j === 0) {
  37608. ringFirstVertex.copyFrom(ringVertex);
  37609. ringFirstNormal.copyFrom(ringNormal);
  37610. }
  37611. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37612. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37613. if (hasRings) {
  37614. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37615. }
  37616. else {
  37617. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37618. }
  37619. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37620. if (faceColors) {
  37621. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37622. }
  37623. }
  37624. // if enclose, add four vertices and their dedicated normals
  37625. if (arc !== 1 && enclose) {
  37626. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37627. positions.push(0, ringVertex.y, 0);
  37628. positions.push(0, ringVertex.y, 0);
  37629. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37630. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37631. quadNormal.normalize();
  37632. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37633. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37634. quadNormal.normalize();
  37635. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37636. if (hasRings) {
  37637. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37638. }
  37639. else {
  37640. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37641. }
  37642. uvs.push(faceUV[s + 1].x, v);
  37643. uvs.push(faceUV[s + 1].z, v);
  37644. if (hasRings) {
  37645. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37646. }
  37647. else {
  37648. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37649. }
  37650. uvs.push(faceUV[s + 2].x, v);
  37651. uvs.push(faceUV[s + 2].z, v);
  37652. if (faceColors) {
  37653. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37654. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37655. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37656. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37657. }
  37658. }
  37659. if (cs !== s) {
  37660. cs = s;
  37661. }
  37662. }
  37663. }
  37664. // indices
  37665. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37666. var s;
  37667. i = 0;
  37668. for (s = 0; s < subdivisions; s++) {
  37669. var i0 = 0;
  37670. var i1 = 0;
  37671. var i2 = 0;
  37672. var i3 = 0;
  37673. for (j = 0; j < tessellation; j++) {
  37674. i0 = i * (e + 1) + j;
  37675. i1 = (i + 1) * (e + 1) + j;
  37676. i2 = i * (e + 1) + (j + 1);
  37677. i3 = (i + 1) * (e + 1) + (j + 1);
  37678. indices.push(i0, i1, i2);
  37679. indices.push(i3, i2, i1);
  37680. }
  37681. if (arc !== 1 && enclose) { // if enclose, add two quads
  37682. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37683. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37684. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37685. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37686. }
  37687. i = (hasRings) ? (i + 2) : (i + 1);
  37688. }
  37689. // Caps
  37690. var createCylinderCap = function (isTop) {
  37691. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37692. if (radius === 0) {
  37693. return;
  37694. }
  37695. // Cap positions, normals & uvs
  37696. var angle;
  37697. var circleVector;
  37698. var i;
  37699. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37700. var c = null;
  37701. if (faceColors) {
  37702. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37703. }
  37704. // cap center
  37705. var vbase = positions.length / 3;
  37706. var offset = isTop ? height / 2 : -height / 2;
  37707. var center = new BABYLON.Vector3(0, offset, 0);
  37708. positions.push(center.x, center.y, center.z);
  37709. normals.push(0, isTop ? 1 : -1, 0);
  37710. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37711. if (c) {
  37712. colors.push(c.r, c.g, c.b, c.a);
  37713. }
  37714. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37715. for (i = 0; i <= tessellation; i++) {
  37716. angle = Math.PI * 2 * i * arc / tessellation;
  37717. var cos = Math.cos(-angle);
  37718. var sin = Math.sin(-angle);
  37719. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37720. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37721. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37722. normals.push(0, isTop ? 1 : -1, 0);
  37723. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37724. if (c) {
  37725. colors.push(c.r, c.g, c.b, c.a);
  37726. }
  37727. }
  37728. // Cap indices
  37729. for (i = 0; i < tessellation; i++) {
  37730. if (!isTop) {
  37731. indices.push(vbase);
  37732. indices.push(vbase + (i + 1));
  37733. indices.push(vbase + (i + 2));
  37734. }
  37735. else {
  37736. indices.push(vbase);
  37737. indices.push(vbase + (i + 2));
  37738. indices.push(vbase + (i + 1));
  37739. }
  37740. }
  37741. };
  37742. // add caps to geometry
  37743. createCylinderCap(false);
  37744. createCylinderCap(true);
  37745. // Sides
  37746. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37747. var vertexData = new VertexData();
  37748. vertexData.indices = indices;
  37749. vertexData.positions = positions;
  37750. vertexData.normals = normals;
  37751. vertexData.uvs = uvs;
  37752. if (faceColors) {
  37753. vertexData.colors = colors;
  37754. }
  37755. return vertexData;
  37756. };
  37757. /**
  37758. * Creates the VertexData for a torus
  37759. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37760. * * diameter the diameter of the torus, optional default 1
  37761. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37762. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37763. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37764. * * 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)
  37765. * * 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)
  37766. * @returns the VertexData of the torus
  37767. */
  37768. VertexData.CreateTorus = function (options) {
  37769. var indices = [];
  37770. var positions = [];
  37771. var normals = [];
  37772. var uvs = [];
  37773. var diameter = options.diameter || 1;
  37774. var thickness = options.thickness || 0.5;
  37775. var tessellation = options.tessellation || 16;
  37776. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37777. var stride = tessellation + 1;
  37778. for (var i = 0; i <= tessellation; i++) {
  37779. var u = i / tessellation;
  37780. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37781. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37782. for (var j = 0; j <= tessellation; j++) {
  37783. var v = 1 - j / tessellation;
  37784. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37785. var dx = Math.cos(innerAngle);
  37786. var dy = Math.sin(innerAngle);
  37787. // Create a vertex.
  37788. var normal = new BABYLON.Vector3(dx, dy, 0);
  37789. var position = normal.scale(thickness / 2);
  37790. var textureCoordinate = new BABYLON.Vector2(u, v);
  37791. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37792. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37793. positions.push(position.x, position.y, position.z);
  37794. normals.push(normal.x, normal.y, normal.z);
  37795. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37796. // And create indices for two triangles.
  37797. var nextI = (i + 1) % stride;
  37798. var nextJ = (j + 1) % stride;
  37799. indices.push(i * stride + j);
  37800. indices.push(i * stride + nextJ);
  37801. indices.push(nextI * stride + j);
  37802. indices.push(i * stride + nextJ);
  37803. indices.push(nextI * stride + nextJ);
  37804. indices.push(nextI * stride + j);
  37805. }
  37806. }
  37807. // Sides
  37808. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37809. // Result
  37810. var vertexData = new VertexData();
  37811. vertexData.indices = indices;
  37812. vertexData.positions = positions;
  37813. vertexData.normals = normals;
  37814. vertexData.uvs = uvs;
  37815. return vertexData;
  37816. };
  37817. /**
  37818. * Creates the VertexData of the LineSystem
  37819. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37820. * - lines an array of lines, each line being an array of successive Vector3
  37821. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37822. * @returns the VertexData of the LineSystem
  37823. */
  37824. VertexData.CreateLineSystem = function (options) {
  37825. var indices = [];
  37826. var positions = [];
  37827. var lines = options.lines;
  37828. var colors = options.colors;
  37829. var vertexColors = [];
  37830. var idx = 0;
  37831. for (var l = 0; l < lines.length; l++) {
  37832. var points = lines[l];
  37833. for (var index = 0; index < points.length; index++) {
  37834. positions.push(points[index].x, points[index].y, points[index].z);
  37835. if (colors) {
  37836. var color = colors[l];
  37837. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37838. }
  37839. if (index > 0) {
  37840. indices.push(idx - 1);
  37841. indices.push(idx);
  37842. }
  37843. idx++;
  37844. }
  37845. }
  37846. var vertexData = new VertexData();
  37847. vertexData.indices = indices;
  37848. vertexData.positions = positions;
  37849. if (colors) {
  37850. vertexData.colors = vertexColors;
  37851. }
  37852. return vertexData;
  37853. };
  37854. /**
  37855. * Create the VertexData for a DashedLines
  37856. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37857. * - points an array successive Vector3
  37858. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37859. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37860. * - dashNb the intended total number of dashes, optional, default 200
  37861. * @returns the VertexData for the DashedLines
  37862. */
  37863. VertexData.CreateDashedLines = function (options) {
  37864. var dashSize = options.dashSize || 3;
  37865. var gapSize = options.gapSize || 1;
  37866. var dashNb = options.dashNb || 200;
  37867. var points = options.points;
  37868. var positions = new Array();
  37869. var indices = new Array();
  37870. var curvect = BABYLON.Vector3.Zero();
  37871. var lg = 0;
  37872. var nb = 0;
  37873. var shft = 0;
  37874. var dashshft = 0;
  37875. var curshft = 0;
  37876. var idx = 0;
  37877. var i = 0;
  37878. for (i = 0; i < points.length - 1; i++) {
  37879. points[i + 1].subtractToRef(points[i], curvect);
  37880. lg += curvect.length();
  37881. }
  37882. shft = lg / dashNb;
  37883. dashshft = dashSize * shft / (dashSize + gapSize);
  37884. for (i = 0; i < points.length - 1; i++) {
  37885. points[i + 1].subtractToRef(points[i], curvect);
  37886. nb = Math.floor(curvect.length() / shft);
  37887. curvect.normalize();
  37888. for (var j = 0; j < nb; j++) {
  37889. curshft = shft * j;
  37890. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37891. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37892. indices.push(idx, idx + 1);
  37893. idx += 2;
  37894. }
  37895. }
  37896. // Result
  37897. var vertexData = new VertexData();
  37898. vertexData.positions = positions;
  37899. vertexData.indices = indices;
  37900. return vertexData;
  37901. };
  37902. /**
  37903. * Creates the VertexData for a Ground
  37904. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37905. * - width the width (x direction) of the ground, optional, default 1
  37906. * - height the height (z direction) of the ground, optional, default 1
  37907. * - subdivisions the number of subdivisions per side, optional, default 1
  37908. * @returns the VertexData of the Ground
  37909. */
  37910. VertexData.CreateGround = function (options) {
  37911. var indices = [];
  37912. var positions = [];
  37913. var normals = [];
  37914. var uvs = [];
  37915. var row, col;
  37916. var width = options.width || 1;
  37917. var height = options.height || 1;
  37918. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37919. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37920. for (row = 0; row <= subdivisionsY; row++) {
  37921. for (col = 0; col <= subdivisionsX; col++) {
  37922. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37923. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37924. positions.push(position.x, position.y, position.z);
  37925. normals.push(normal.x, normal.y, normal.z);
  37926. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37927. }
  37928. }
  37929. for (row = 0; row < subdivisionsY; row++) {
  37930. for (col = 0; col < subdivisionsX; col++) {
  37931. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37932. indices.push(col + 1 + row * (subdivisionsX + 1));
  37933. indices.push(col + row * (subdivisionsX + 1));
  37934. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37935. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37936. indices.push(col + row * (subdivisionsX + 1));
  37937. }
  37938. }
  37939. // Result
  37940. var vertexData = new VertexData();
  37941. vertexData.indices = indices;
  37942. vertexData.positions = positions;
  37943. vertexData.normals = normals;
  37944. vertexData.uvs = uvs;
  37945. return vertexData;
  37946. };
  37947. /**
  37948. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37949. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37950. * * xmin the ground minimum X coordinate, optional, default -1
  37951. * * zmin the ground minimum Z coordinate, optional, default -1
  37952. * * xmax the ground maximum X coordinate, optional, default 1
  37953. * * zmax the ground maximum Z coordinate, optional, default 1
  37954. * * 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}
  37955. * * 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}
  37956. * @returns the VertexData of the TiledGround
  37957. */
  37958. VertexData.CreateTiledGround = function (options) {
  37959. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37960. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37961. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37962. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37963. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37964. var precision = options.precision || { w: 1, h: 1 };
  37965. var indices = new Array();
  37966. var positions = new Array();
  37967. var normals = new Array();
  37968. var uvs = new Array();
  37969. var row, col, tileRow, tileCol;
  37970. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37971. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37972. precision.w = (precision.w < 1) ? 1 : precision.w;
  37973. precision.h = (precision.h < 1) ? 1 : precision.h;
  37974. var tileSize = {
  37975. 'w': (xmax - xmin) / subdivisions.w,
  37976. 'h': (zmax - zmin) / subdivisions.h
  37977. };
  37978. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37979. // Indices
  37980. var base = positions.length / 3;
  37981. var rowLength = precision.w + 1;
  37982. for (row = 0; row < precision.h; row++) {
  37983. for (col = 0; col < precision.w; col++) {
  37984. var square = [
  37985. base + col + row * rowLength,
  37986. base + (col + 1) + row * rowLength,
  37987. base + (col + 1) + (row + 1) * rowLength,
  37988. base + col + (row + 1) * rowLength
  37989. ];
  37990. indices.push(square[1]);
  37991. indices.push(square[2]);
  37992. indices.push(square[3]);
  37993. indices.push(square[0]);
  37994. indices.push(square[1]);
  37995. indices.push(square[3]);
  37996. }
  37997. }
  37998. // Position, normals and uvs
  37999. var position = BABYLON.Vector3.Zero();
  38000. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38001. for (row = 0; row <= precision.h; row++) {
  38002. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38003. for (col = 0; col <= precision.w; col++) {
  38004. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38005. position.y = 0;
  38006. positions.push(position.x, position.y, position.z);
  38007. normals.push(normal.x, normal.y, normal.z);
  38008. uvs.push(col / precision.w, row / precision.h);
  38009. }
  38010. }
  38011. }
  38012. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38013. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38014. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38015. }
  38016. }
  38017. // Result
  38018. var vertexData = new VertexData();
  38019. vertexData.indices = indices;
  38020. vertexData.positions = positions;
  38021. vertexData.normals = normals;
  38022. vertexData.uvs = uvs;
  38023. return vertexData;
  38024. };
  38025. /**
  38026. * Creates the VertexData of the Ground designed from a heightmap
  38027. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38028. * * width the width (x direction) of the ground
  38029. * * height the height (z direction) of the ground
  38030. * * subdivisions the number of subdivisions per side
  38031. * * minHeight the minimum altitude on the ground, optional, default 0
  38032. * * maxHeight the maximum altitude on the ground, optional default 1
  38033. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38034. * * buffer the array holding the image color data
  38035. * * bufferWidth the width of image
  38036. * * bufferHeight the height of image
  38037. * @returns the VertexData of the Ground designed from a heightmap
  38038. */
  38039. VertexData.CreateGroundFromHeightMap = function (options) {
  38040. var indices = [];
  38041. var positions = [];
  38042. var normals = [];
  38043. var uvs = [];
  38044. var row, col;
  38045. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38046. // Vertices
  38047. for (row = 0; row <= options.subdivisions; row++) {
  38048. for (col = 0; col <= options.subdivisions; col++) {
  38049. 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));
  38050. // Compute height
  38051. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38052. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38053. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38054. var r = options.buffer[pos] / 255.0;
  38055. var g = options.buffer[pos + 1] / 255.0;
  38056. var b = options.buffer[pos + 2] / 255.0;
  38057. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38058. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38059. // Add vertex
  38060. positions.push(position.x, position.y, position.z);
  38061. normals.push(0, 0, 0);
  38062. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38063. }
  38064. }
  38065. // Indices
  38066. for (row = 0; row < options.subdivisions; row++) {
  38067. for (col = 0; col < options.subdivisions; col++) {
  38068. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38069. indices.push(col + 1 + row * (options.subdivisions + 1));
  38070. indices.push(col + row * (options.subdivisions + 1));
  38071. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38072. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38073. indices.push(col + row * (options.subdivisions + 1));
  38074. }
  38075. }
  38076. // Normals
  38077. VertexData.ComputeNormals(positions, indices, normals);
  38078. // Result
  38079. var vertexData = new VertexData();
  38080. vertexData.indices = indices;
  38081. vertexData.positions = positions;
  38082. vertexData.normals = normals;
  38083. vertexData.uvs = uvs;
  38084. return vertexData;
  38085. };
  38086. /**
  38087. * Creates the VertexData for a Plane
  38088. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38089. * * size sets the width and height of the plane to the value of size, optional default 1
  38090. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38091. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38092. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38093. * * 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)
  38094. * * 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)
  38095. * @returns the VertexData of the box
  38096. */
  38097. VertexData.CreatePlane = function (options) {
  38098. var indices = [];
  38099. var positions = [];
  38100. var normals = [];
  38101. var uvs = [];
  38102. var width = options.width || options.size || 1;
  38103. var height = options.height || options.size || 1;
  38104. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38105. // Vertices
  38106. var halfWidth = width / 2.0;
  38107. var halfHeight = height / 2.0;
  38108. positions.push(-halfWidth, -halfHeight, 0);
  38109. normals.push(0, 0, -1.0);
  38110. uvs.push(0.0, 0.0);
  38111. positions.push(halfWidth, -halfHeight, 0);
  38112. normals.push(0, 0, -1.0);
  38113. uvs.push(1.0, 0.0);
  38114. positions.push(halfWidth, halfHeight, 0);
  38115. normals.push(0, 0, -1.0);
  38116. uvs.push(1.0, 1.0);
  38117. positions.push(-halfWidth, halfHeight, 0);
  38118. normals.push(0, 0, -1.0);
  38119. uvs.push(0.0, 1.0);
  38120. // Indices
  38121. indices.push(0);
  38122. indices.push(1);
  38123. indices.push(2);
  38124. indices.push(0);
  38125. indices.push(2);
  38126. indices.push(3);
  38127. // Sides
  38128. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38129. // Result
  38130. var vertexData = new VertexData();
  38131. vertexData.indices = indices;
  38132. vertexData.positions = positions;
  38133. vertexData.normals = normals;
  38134. vertexData.uvs = uvs;
  38135. return vertexData;
  38136. };
  38137. /**
  38138. * Creates the VertexData of the Disc or regular Polygon
  38139. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38140. * * radius the radius of the disc, optional default 0.5
  38141. * * tessellation the number of polygon sides, optional, default 64
  38142. * * 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
  38143. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38144. * * 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)
  38145. * * 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)
  38146. * @returns the VertexData of the box
  38147. */
  38148. VertexData.CreateDisc = function (options) {
  38149. var positions = new Array();
  38150. var indices = new Array();
  38151. var normals = new Array();
  38152. var uvs = new Array();
  38153. var radius = options.radius || 0.5;
  38154. var tessellation = options.tessellation || 64;
  38155. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38156. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38157. // positions and uvs
  38158. positions.push(0, 0, 0); // disc center first
  38159. uvs.push(0.5, 0.5);
  38160. var theta = Math.PI * 2 * arc;
  38161. var step = theta / tessellation;
  38162. for (var a = 0; a < theta; a += step) {
  38163. var x = Math.cos(a);
  38164. var y = Math.sin(a);
  38165. var u = (x + 1) / 2;
  38166. var v = (1 - y) / 2;
  38167. positions.push(radius * x, radius * y, 0);
  38168. uvs.push(u, v);
  38169. }
  38170. if (arc === 1) {
  38171. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38172. uvs.push(uvs[2], uvs[3]);
  38173. }
  38174. //indices
  38175. var vertexNb = positions.length / 3;
  38176. for (var i = 1; i < vertexNb - 1; i++) {
  38177. indices.push(i + 1, 0, i);
  38178. }
  38179. // result
  38180. VertexData.ComputeNormals(positions, indices, normals);
  38181. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38182. var vertexData = new VertexData();
  38183. vertexData.indices = indices;
  38184. vertexData.positions = positions;
  38185. vertexData.normals = normals;
  38186. vertexData.uvs = uvs;
  38187. return vertexData;
  38188. };
  38189. /**
  38190. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38191. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38192. * @param polygon a mesh built from polygonTriangulation.build()
  38193. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38194. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38195. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38196. * @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)
  38197. * @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)
  38198. * @returns the VertexData of the Polygon
  38199. */
  38200. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38201. var faceUV = fUV || new Array(3);
  38202. var faceColors = fColors;
  38203. var colors = [];
  38204. // default face colors and UV if undefined
  38205. for (var f = 0; f < 3; f++) {
  38206. if (faceUV[f] === undefined) {
  38207. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38208. }
  38209. if (faceColors && faceColors[f] === undefined) {
  38210. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38211. }
  38212. }
  38213. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38214. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38215. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38216. var indices = polygon.getIndices();
  38217. // set face colours and textures
  38218. var idx = 0;
  38219. var face = 0;
  38220. for (var index = 0; index < normals.length; index += 3) {
  38221. //Edge Face no. 1
  38222. if (Math.abs(normals[index + 1]) < 0.001) {
  38223. face = 1;
  38224. }
  38225. //Top Face no. 0
  38226. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38227. face = 0;
  38228. }
  38229. //Bottom Face no. 2
  38230. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38231. face = 2;
  38232. }
  38233. idx = index / 3;
  38234. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38235. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38236. if (faceColors) {
  38237. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38238. }
  38239. }
  38240. // sides
  38241. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38242. // Result
  38243. var vertexData = new VertexData();
  38244. vertexData.indices = indices;
  38245. vertexData.positions = positions;
  38246. vertexData.normals = normals;
  38247. vertexData.uvs = uvs;
  38248. if (faceColors) {
  38249. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38250. vertexData.colors = totalColors;
  38251. }
  38252. return vertexData;
  38253. };
  38254. /**
  38255. * Creates the VertexData of the IcoSphere
  38256. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38257. * * radius the radius of the IcoSphere, optional default 1
  38258. * * radiusX allows stretching in the x direction, optional, default radius
  38259. * * radiusY allows stretching in the y direction, optional, default radius
  38260. * * radiusZ allows stretching in the z direction, optional, default radius
  38261. * * flat when true creates a flat shaded mesh, optional, default true
  38262. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38263. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38264. * * 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)
  38265. * * 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)
  38266. * @returns the VertexData of the IcoSphere
  38267. */
  38268. VertexData.CreateIcoSphere = function (options) {
  38269. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38270. var radius = options.radius || 1;
  38271. var flat = (options.flat === undefined) ? true : options.flat;
  38272. var subdivisions = options.subdivisions || 4;
  38273. var radiusX = options.radiusX || radius;
  38274. var radiusY = options.radiusY || radius;
  38275. var radiusZ = options.radiusZ || radius;
  38276. var t = (1 + Math.sqrt(5)) / 2;
  38277. // 12 vertex x,y,z
  38278. var ico_vertices = [
  38279. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38280. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38281. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38282. ];
  38283. // index of 3 vertex makes a face of icopshere
  38284. var ico_indices = [
  38285. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38286. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38287. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38288. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38289. ];
  38290. // vertex for uv have aliased position, not for UV
  38291. var vertices_unalias_id = [
  38292. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38293. // vertex alias
  38294. 0,
  38295. 2,
  38296. 3,
  38297. 3,
  38298. 3,
  38299. 4,
  38300. 7,
  38301. 8,
  38302. 9,
  38303. 9,
  38304. 10,
  38305. 11 // 23: B + 12
  38306. ];
  38307. // uv as integer step (not pixels !)
  38308. var ico_vertexuv = [
  38309. 5, 1, 3, 1, 6, 4, 0, 0,
  38310. 5, 3, 4, 2, 2, 2, 4, 0,
  38311. 2, 0, 1, 1, 6, 0, 6, 2,
  38312. // vertex alias (for same vertex on different faces)
  38313. 0, 4,
  38314. 3, 3,
  38315. 4, 4,
  38316. 3, 1,
  38317. 4, 2,
  38318. 4, 4,
  38319. 0, 2,
  38320. 1, 1,
  38321. 2, 2,
  38322. 3, 3,
  38323. 1, 3,
  38324. 2, 4 // 23: B + 12
  38325. ];
  38326. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38327. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38328. // First island of uv mapping
  38329. // v = 4h 3+ 2
  38330. // v = 3h 9+ 4
  38331. // v = 2h 9+ 5 B
  38332. // v = 1h 9 1 0
  38333. // v = 0h 3 8 7 A
  38334. // u = 0 1 2 3 4 5 6 *a
  38335. // Second island of uv mapping
  38336. // v = 4h 0+ B+ 4+
  38337. // v = 3h A+ 2+
  38338. // v = 2h 7+ 6 3+
  38339. // v = 1h 8+ 3+
  38340. // v = 0h
  38341. // u = 0 1 2 3 4 5 6 *a
  38342. // Face layout on texture UV mapping
  38343. // ============
  38344. // \ 4 /\ 16 / ======
  38345. // \ / \ / /\ 11 /
  38346. // \/ 7 \/ / \ /
  38347. // ======= / 10 \/
  38348. // /\ 17 /\ =======
  38349. // / \ / \ \ 15 /\
  38350. // / 8 \/ 12 \ \ / \
  38351. // ============ \/ 6 \
  38352. // \ 18 /\ ============
  38353. // \ / \ \ 5 /\ 0 /
  38354. // \/ 13 \ \ / \ /
  38355. // ======= \/ 1 \/
  38356. // =============
  38357. // /\ 19 /\ 2 /\
  38358. // / \ / \ / \
  38359. // / 14 \/ 9 \/ 3 \
  38360. // ===================
  38361. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38362. var ustep = 138 / 1024;
  38363. var vstep = 239 / 1024;
  38364. var uoffset = 60 / 1024;
  38365. var voffset = 26 / 1024;
  38366. // Second island should have margin, not to touch the first island
  38367. // avoid any borderline artefact in pixel rounding
  38368. var island_u_offset = -40 / 1024;
  38369. var island_v_offset = +20 / 1024;
  38370. // face is either island 0 or 1 :
  38371. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38372. var island = [
  38373. 0, 0, 0, 0, 1,
  38374. 0, 0, 1, 1, 0,
  38375. 0, 0, 1, 1, 0,
  38376. 0, 1, 1, 1, 0 // 15 - 19
  38377. ];
  38378. var indices = new Array();
  38379. var positions = new Array();
  38380. var normals = new Array();
  38381. var uvs = new Array();
  38382. var current_indice = 0;
  38383. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38384. var face_vertex_pos = new Array(3);
  38385. var face_vertex_uv = new Array(3);
  38386. var v012;
  38387. for (v012 = 0; v012 < 3; v012++) {
  38388. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38389. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38390. }
  38391. // create all with normals
  38392. for (var face = 0; face < 20; face++) {
  38393. // 3 vertex per face
  38394. for (v012 = 0; v012 < 3; v012++) {
  38395. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38396. var v_id = ico_indices[3 * face + v012];
  38397. // vertex have 3D position (x,y,z)
  38398. 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]);
  38399. // Normalize to get normal, then scale to radius
  38400. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38401. // uv Coordinates from vertex ID
  38402. 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);
  38403. }
  38404. // Subdivide the face (interpolate pos, norm, uv)
  38405. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38406. // - norm is linear interpolation of vertex corner normal
  38407. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38408. // - uv is linear interpolation
  38409. //
  38410. // Topology is as below for sub-divide by 2
  38411. // vertex shown as v0,v1,v2
  38412. // interp index is i1 to progress in range [v0,v1[
  38413. // interp index is i2 to progress in range [v0,v2[
  38414. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38415. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38416. //
  38417. //
  38418. // i2 v2
  38419. // ^ ^
  38420. // / / \
  38421. // / / \
  38422. // / / \
  38423. // / / (0,1) \
  38424. // / #---------\
  38425. // / / \ (0,0)'/ \
  38426. // / / \ / \
  38427. // / / \ / \
  38428. // / / (0,0) \ / (1,0) \
  38429. // / #---------#---------\
  38430. // v0 v1
  38431. //
  38432. // --------------------> i1
  38433. //
  38434. // interp of (i1,i2):
  38435. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38436. // along i1 : lerp(x0,x1, i1/(S-i2))
  38437. //
  38438. // centroid of triangle is needed to get help normal computation
  38439. // (c1,c2) are used for centroid location
  38440. var interp_vertex = function (i1, i2, c1, c2) {
  38441. // vertex is interpolated from
  38442. // - face_vertex_pos[0..2]
  38443. // - face_vertex_uv[0..2]
  38444. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38445. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38446. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38447. pos_interp.normalize();
  38448. var vertex_normal;
  38449. if (flat) {
  38450. // in flat mode, recalculate normal as face centroid normal
  38451. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38452. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38453. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38454. }
  38455. else {
  38456. // in smooth mode, recalculate normal from each single vertex position
  38457. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38458. }
  38459. // Vertex normal need correction due to X,Y,Z radius scaling
  38460. vertex_normal.x /= radiusX;
  38461. vertex_normal.y /= radiusY;
  38462. vertex_normal.z /= radiusZ;
  38463. vertex_normal.normalize();
  38464. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38465. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38466. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38467. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38468. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38469. uvs.push(uv_interp.x, uv_interp.y);
  38470. // push each vertex has member of a face
  38471. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38472. indices.push(current_indice);
  38473. current_indice++;
  38474. };
  38475. for (var i2 = 0; i2 < subdivisions; i2++) {
  38476. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38477. // face : (i1,i2) for /\ :
  38478. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38479. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38480. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38481. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38482. if (i1 + i2 + 1 < subdivisions) {
  38483. // face : (i1,i2)' for \/ :
  38484. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38485. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38486. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38487. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38488. }
  38489. }
  38490. }
  38491. }
  38492. // Sides
  38493. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38494. // Result
  38495. var vertexData = new VertexData();
  38496. vertexData.indices = indices;
  38497. vertexData.positions = positions;
  38498. vertexData.normals = normals;
  38499. vertexData.uvs = uvs;
  38500. return vertexData;
  38501. };
  38502. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38503. /**
  38504. * Creates the VertexData for a Polyhedron
  38505. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38506. * * type provided types are:
  38507. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38508. * * 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)
  38509. * * size the size of the IcoSphere, optional default 1
  38510. * * sizeX allows stretching in the x direction, optional, default size
  38511. * * sizeY allows stretching in the y direction, optional, default size
  38512. * * sizeZ allows stretching in the z direction, optional, default size
  38513. * * 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
  38514. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38515. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38516. * * flat when true creates a flat shaded mesh, optional, default true
  38517. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38518. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38519. * * 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)
  38520. * * 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)
  38521. * @returns the VertexData of the Polyhedron
  38522. */
  38523. VertexData.CreatePolyhedron = function (options) {
  38524. // provided polyhedron types :
  38525. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38526. // 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)
  38527. var polyhedra = [];
  38528. 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]] };
  38529. 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]] };
  38530. polyhedra[2] = {
  38531. 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]],
  38532. 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]]
  38533. };
  38534. polyhedra[3] = {
  38535. 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]],
  38536. 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]]
  38537. };
  38538. polyhedra[4] = {
  38539. 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]],
  38540. 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]]
  38541. };
  38542. 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]] };
  38543. 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]] };
  38544. 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]] };
  38545. 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]] };
  38546. 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]] };
  38547. 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]] };
  38548. 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]] };
  38549. 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]] };
  38550. 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]] };
  38551. polyhedra[14] = {
  38552. 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]],
  38553. 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]]
  38554. };
  38555. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38556. var size = options.size;
  38557. var sizeX = options.sizeX || size || 1;
  38558. var sizeY = options.sizeY || size || 1;
  38559. var sizeZ = options.sizeZ || size || 1;
  38560. var data = options.custom || polyhedra[type];
  38561. var nbfaces = data.face.length;
  38562. var faceUV = options.faceUV || new Array(nbfaces);
  38563. var faceColors = options.faceColors;
  38564. var flat = (options.flat === undefined) ? true : options.flat;
  38565. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38566. var positions = new Array();
  38567. var indices = new Array();
  38568. var normals = new Array();
  38569. var uvs = new Array();
  38570. var colors = new Array();
  38571. var index = 0;
  38572. var faceIdx = 0; // face cursor in the array "indexes"
  38573. var indexes = new Array();
  38574. var i = 0;
  38575. var f = 0;
  38576. var u, v, ang, x, y, tmp;
  38577. // default face colors and UV if undefined
  38578. if (flat) {
  38579. for (f = 0; f < nbfaces; f++) {
  38580. if (faceColors && faceColors[f] === undefined) {
  38581. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38582. }
  38583. if (faceUV && faceUV[f] === undefined) {
  38584. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38585. }
  38586. }
  38587. }
  38588. if (!flat) {
  38589. for (i = 0; i < data.vertex.length; i++) {
  38590. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38591. uvs.push(0, 0);
  38592. }
  38593. for (f = 0; f < nbfaces; f++) {
  38594. for (i = 0; i < data.face[f].length - 2; i++) {
  38595. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38596. }
  38597. }
  38598. }
  38599. else {
  38600. for (f = 0; f < nbfaces; f++) {
  38601. var fl = data.face[f].length; // number of vertices of the current face
  38602. ang = 2 * Math.PI / fl;
  38603. x = 0.5 * Math.tan(ang / 2);
  38604. y = 0.5;
  38605. // positions, uvs, colors
  38606. for (i = 0; i < fl; i++) {
  38607. // positions
  38608. 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);
  38609. indexes.push(index);
  38610. index++;
  38611. // uvs
  38612. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38613. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38614. uvs.push(u, v);
  38615. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38616. y = x * Math.sin(ang) + y * Math.cos(ang);
  38617. x = tmp;
  38618. // colors
  38619. if (faceColors) {
  38620. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38621. }
  38622. }
  38623. // indices from indexes
  38624. for (i = 0; i < fl - 2; i++) {
  38625. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38626. }
  38627. faceIdx += fl;
  38628. }
  38629. }
  38630. VertexData.ComputeNormals(positions, indices, normals);
  38631. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38632. var vertexData = new VertexData();
  38633. vertexData.positions = positions;
  38634. vertexData.indices = indices;
  38635. vertexData.normals = normals;
  38636. vertexData.uvs = uvs;
  38637. if (faceColors && flat) {
  38638. vertexData.colors = colors;
  38639. }
  38640. return vertexData;
  38641. };
  38642. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38643. /**
  38644. * Creates the VertexData for a TorusKnot
  38645. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38646. * * radius the radius of the torus knot, optional, default 2
  38647. * * tube the thickness of the tube, optional, default 0.5
  38648. * * radialSegments the number of sides on each tube segments, optional, default 32
  38649. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38650. * * p the number of windings around the z axis, optional, default 2
  38651. * * q the number of windings around the x axis, optional, default 3
  38652. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38653. * * 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)
  38654. * * 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)
  38655. * @returns the VertexData of the Torus Knot
  38656. */
  38657. VertexData.CreateTorusKnot = function (options) {
  38658. var indices = new Array();
  38659. var positions = new Array();
  38660. var normals = new Array();
  38661. var uvs = new Array();
  38662. var radius = options.radius || 2;
  38663. var tube = options.tube || 0.5;
  38664. var radialSegments = options.radialSegments || 32;
  38665. var tubularSegments = options.tubularSegments || 32;
  38666. var p = options.p || 2;
  38667. var q = options.q || 3;
  38668. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38669. // Helper
  38670. var getPos = function (angle) {
  38671. var cu = Math.cos(angle);
  38672. var su = Math.sin(angle);
  38673. var quOverP = q / p * angle;
  38674. var cs = Math.cos(quOverP);
  38675. var tx = radius * (2 + cs) * 0.5 * cu;
  38676. var ty = radius * (2 + cs) * su * 0.5;
  38677. var tz = radius * Math.sin(quOverP) * 0.5;
  38678. return new BABYLON.Vector3(tx, ty, tz);
  38679. };
  38680. // Vertices
  38681. var i;
  38682. var j;
  38683. for (i = 0; i <= radialSegments; i++) {
  38684. var modI = i % radialSegments;
  38685. var u = modI / radialSegments * 2 * p * Math.PI;
  38686. var p1 = getPos(u);
  38687. var p2 = getPos(u + 0.01);
  38688. var tang = p2.subtract(p1);
  38689. var n = p2.add(p1);
  38690. var bitan = BABYLON.Vector3.Cross(tang, n);
  38691. n = BABYLON.Vector3.Cross(bitan, tang);
  38692. bitan.normalize();
  38693. n.normalize();
  38694. for (j = 0; j < tubularSegments; j++) {
  38695. var modJ = j % tubularSegments;
  38696. var v = modJ / tubularSegments * 2 * Math.PI;
  38697. var cx = -tube * Math.cos(v);
  38698. var cy = tube * Math.sin(v);
  38699. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38700. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38701. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38702. uvs.push(i / radialSegments);
  38703. uvs.push(j / tubularSegments);
  38704. }
  38705. }
  38706. for (i = 0; i < radialSegments; i++) {
  38707. for (j = 0; j < tubularSegments; j++) {
  38708. var jNext = (j + 1) % tubularSegments;
  38709. var a = i * tubularSegments + j;
  38710. var b = (i + 1) * tubularSegments + j;
  38711. var c = (i + 1) * tubularSegments + jNext;
  38712. var d = i * tubularSegments + jNext;
  38713. indices.push(d);
  38714. indices.push(b);
  38715. indices.push(a);
  38716. indices.push(d);
  38717. indices.push(c);
  38718. indices.push(b);
  38719. }
  38720. }
  38721. // Normals
  38722. VertexData.ComputeNormals(positions, indices, normals);
  38723. // Sides
  38724. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38725. // Result
  38726. var vertexData = new VertexData();
  38727. vertexData.indices = indices;
  38728. vertexData.positions = positions;
  38729. vertexData.normals = normals;
  38730. vertexData.uvs = uvs;
  38731. return vertexData;
  38732. };
  38733. // Tools
  38734. /**
  38735. * Compute normals for given positions and indices
  38736. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38737. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38738. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38739. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38740. * * facetNormals : optional array of facet normals (vector3)
  38741. * * facetPositions : optional array of facet positions (vector3)
  38742. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38743. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38744. * * bInfo : optional bounding info, required for facetPartitioning computation
  38745. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38746. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38747. * * useRightHandedSystem: optional boolean to for right handed system computation
  38748. * * depthSort : optional boolean to enable the facet depth sort computation
  38749. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38750. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38751. */
  38752. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38753. // temporary scalar variables
  38754. var index = 0; // facet index
  38755. var p1p2x = 0.0; // p1p2 vector x coordinate
  38756. var p1p2y = 0.0; // p1p2 vector y coordinate
  38757. var p1p2z = 0.0; // p1p2 vector z coordinate
  38758. var p3p2x = 0.0; // p3p2 vector x coordinate
  38759. var p3p2y = 0.0; // p3p2 vector y coordinate
  38760. var p3p2z = 0.0; // p3p2 vector z coordinate
  38761. var faceNormalx = 0.0; // facet normal x coordinate
  38762. var faceNormaly = 0.0; // facet normal y coordinate
  38763. var faceNormalz = 0.0; // facet normal z coordinate
  38764. var length = 0.0; // facet normal length before normalization
  38765. var v1x = 0; // vector1 x index in the positions array
  38766. var v1y = 0; // vector1 y index in the positions array
  38767. var v1z = 0; // vector1 z index in the positions array
  38768. var v2x = 0; // vector2 x index in the positions array
  38769. var v2y = 0; // vector2 y index in the positions array
  38770. var v2z = 0; // vector2 z index in the positions array
  38771. var v3x = 0; // vector3 x index in the positions array
  38772. var v3y = 0; // vector3 y index in the positions array
  38773. var v3z = 0; // vector3 z index in the positions array
  38774. var computeFacetNormals = false;
  38775. var computeFacetPositions = false;
  38776. var computeFacetPartitioning = false;
  38777. var computeDepthSort = false;
  38778. var faceNormalSign = 1;
  38779. var ratio = 0;
  38780. var distanceTo = null;
  38781. if (options) {
  38782. computeFacetNormals = (options.facetNormals) ? true : false;
  38783. computeFacetPositions = (options.facetPositions) ? true : false;
  38784. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38785. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38786. ratio = options.ratio || 0;
  38787. computeDepthSort = (options.depthSort) ? true : false;
  38788. distanceTo = (options.distanceTo);
  38789. if (computeDepthSort) {
  38790. if (distanceTo === undefined) {
  38791. distanceTo = BABYLON.Vector3.Zero();
  38792. }
  38793. var depthSortedFacets = options.depthSortedFacets;
  38794. }
  38795. }
  38796. // facetPartitioning reinit if needed
  38797. var xSubRatio = 0;
  38798. var ySubRatio = 0;
  38799. var zSubRatio = 0;
  38800. var subSq = 0;
  38801. if (computeFacetPartitioning && options && options.bbSize) {
  38802. var ox = 0; // X partitioning index for facet position
  38803. var oy = 0; // Y partinioning index for facet position
  38804. var oz = 0; // Z partinioning index for facet position
  38805. var b1x = 0; // X partitioning index for facet v1 vertex
  38806. var b1y = 0; // Y partitioning index for facet v1 vertex
  38807. var b1z = 0; // z partitioning index for facet v1 vertex
  38808. var b2x = 0; // X partitioning index for facet v2 vertex
  38809. var b2y = 0; // Y partitioning index for facet v2 vertex
  38810. var b2z = 0; // Z partitioning index for facet v2 vertex
  38811. var b3x = 0; // X partitioning index for facet v3 vertex
  38812. var b3y = 0; // Y partitioning index for facet v3 vertex
  38813. var b3z = 0; // Z partitioning index for facet v3 vertex
  38814. var block_idx_o = 0; // facet barycenter block index
  38815. var block_idx_v1 = 0; // v1 vertex block index
  38816. var block_idx_v2 = 0; // v2 vertex block index
  38817. var block_idx_v3 = 0; // v3 vertex block index
  38818. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38819. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38820. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38821. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38822. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38823. subSq = options.subDiv.max * options.subDiv.max;
  38824. options.facetPartitioning.length = 0;
  38825. }
  38826. // reset the normals
  38827. for (index = 0; index < positions.length; index++) {
  38828. normals[index] = 0.0;
  38829. }
  38830. // Loop : 1 indice triplet = 1 facet
  38831. var nbFaces = (indices.length / 3) | 0;
  38832. for (index = 0; index < nbFaces; index++) {
  38833. // get the indexes of the coordinates of each vertex of the facet
  38834. v1x = indices[index * 3] * 3;
  38835. v1y = v1x + 1;
  38836. v1z = v1x + 2;
  38837. v2x = indices[index * 3 + 1] * 3;
  38838. v2y = v2x + 1;
  38839. v2z = v2x + 2;
  38840. v3x = indices[index * 3 + 2] * 3;
  38841. v3y = v3x + 1;
  38842. v3z = v3x + 2;
  38843. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38844. p1p2y = positions[v1y] - positions[v2y];
  38845. p1p2z = positions[v1z] - positions[v2z];
  38846. p3p2x = positions[v3x] - positions[v2x];
  38847. p3p2y = positions[v3y] - positions[v2y];
  38848. p3p2z = positions[v3z] - positions[v2z];
  38849. // compute the face normal with the cross product
  38850. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38851. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38852. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38853. // normalize this normal and store it in the array facetData
  38854. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38855. length = (length === 0) ? 1.0 : length;
  38856. faceNormalx /= length;
  38857. faceNormaly /= length;
  38858. faceNormalz /= length;
  38859. if (computeFacetNormals && options) {
  38860. options.facetNormals[index].x = faceNormalx;
  38861. options.facetNormals[index].y = faceNormaly;
  38862. options.facetNormals[index].z = faceNormalz;
  38863. }
  38864. if (computeFacetPositions && options) {
  38865. // compute and the facet barycenter coordinates in the array facetPositions
  38866. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38867. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38868. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38869. }
  38870. if (computeFacetPartitioning && options) {
  38871. // store the facet indexes in arrays in the main facetPartitioning array :
  38872. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38873. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38874. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38875. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38876. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38877. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38878. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38879. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38880. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38881. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38882. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38883. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38884. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38885. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38886. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38887. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38888. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38889. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38890. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38891. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38892. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38893. // push each facet index in each block containing the vertex
  38894. options.facetPartitioning[block_idx_v1].push(index);
  38895. if (block_idx_v2 != block_idx_v1) {
  38896. options.facetPartitioning[block_idx_v2].push(index);
  38897. }
  38898. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38899. options.facetPartitioning[block_idx_v3].push(index);
  38900. }
  38901. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38902. options.facetPartitioning[block_idx_o].push(index);
  38903. }
  38904. }
  38905. if (computeDepthSort && options && options.facetPositions) {
  38906. var dsf = depthSortedFacets[index];
  38907. dsf.ind = index * 3;
  38908. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38909. }
  38910. // compute the normals anyway
  38911. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38912. normals[v1y] += faceNormaly;
  38913. normals[v1z] += faceNormalz;
  38914. normals[v2x] += faceNormalx;
  38915. normals[v2y] += faceNormaly;
  38916. normals[v2z] += faceNormalz;
  38917. normals[v3x] += faceNormalx;
  38918. normals[v3y] += faceNormaly;
  38919. normals[v3z] += faceNormalz;
  38920. }
  38921. // last normalization of each normal
  38922. for (index = 0; index < normals.length / 3; index++) {
  38923. faceNormalx = normals[index * 3];
  38924. faceNormaly = normals[index * 3 + 1];
  38925. faceNormalz = normals[index * 3 + 2];
  38926. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38927. length = (length === 0) ? 1.0 : length;
  38928. faceNormalx /= length;
  38929. faceNormaly /= length;
  38930. faceNormalz /= length;
  38931. normals[index * 3] = faceNormalx;
  38932. normals[index * 3 + 1] = faceNormaly;
  38933. normals[index * 3 + 2] = faceNormalz;
  38934. }
  38935. };
  38936. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38937. var li = indices.length;
  38938. var ln = normals.length;
  38939. var i;
  38940. var n;
  38941. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38942. switch (sideOrientation) {
  38943. case BABYLON.Mesh.FRONTSIDE:
  38944. // nothing changed
  38945. break;
  38946. case BABYLON.Mesh.BACKSIDE:
  38947. var tmp;
  38948. // indices
  38949. for (i = 0; i < li; i += 3) {
  38950. tmp = indices[i];
  38951. indices[i] = indices[i + 2];
  38952. indices[i + 2] = tmp;
  38953. }
  38954. // normals
  38955. for (n = 0; n < ln; n++) {
  38956. normals[n] = -normals[n];
  38957. }
  38958. break;
  38959. case BABYLON.Mesh.DOUBLESIDE:
  38960. // positions
  38961. var lp = positions.length;
  38962. var l = lp / 3;
  38963. for (var p = 0; p < lp; p++) {
  38964. positions[lp + p] = positions[p];
  38965. }
  38966. // indices
  38967. for (i = 0; i < li; i += 3) {
  38968. indices[i + li] = indices[i + 2] + l;
  38969. indices[i + 1 + li] = indices[i + 1] + l;
  38970. indices[i + 2 + li] = indices[i] + l;
  38971. }
  38972. // normals
  38973. for (n = 0; n < ln; n++) {
  38974. normals[ln + n] = -normals[n];
  38975. }
  38976. // uvs
  38977. var lu = uvs.length;
  38978. var u = 0;
  38979. for (u = 0; u < lu; u++) {
  38980. uvs[u + lu] = uvs[u];
  38981. }
  38982. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38983. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38984. u = 0;
  38985. for (i = 0; i < lu / 2; i++) {
  38986. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38987. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38988. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38989. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38990. u += 2;
  38991. }
  38992. break;
  38993. }
  38994. };
  38995. /**
  38996. * Applies VertexData created from the imported parameters to the geometry
  38997. * @param parsedVertexData the parsed data from an imported file
  38998. * @param geometry the geometry to apply the VertexData to
  38999. */
  39000. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39001. var vertexData = new VertexData();
  39002. // positions
  39003. var positions = parsedVertexData.positions;
  39004. if (positions) {
  39005. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39006. }
  39007. // normals
  39008. var normals = parsedVertexData.normals;
  39009. if (normals) {
  39010. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39011. }
  39012. // tangents
  39013. var tangents = parsedVertexData.tangents;
  39014. if (tangents) {
  39015. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39016. }
  39017. // uvs
  39018. var uvs = parsedVertexData.uvs;
  39019. if (uvs) {
  39020. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39021. }
  39022. // uv2s
  39023. var uv2s = parsedVertexData.uv2s;
  39024. if (uv2s) {
  39025. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39026. }
  39027. // uv3s
  39028. var uv3s = parsedVertexData.uv3s;
  39029. if (uv3s) {
  39030. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39031. }
  39032. // uv4s
  39033. var uv4s = parsedVertexData.uv4s;
  39034. if (uv4s) {
  39035. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39036. }
  39037. // uv5s
  39038. var uv5s = parsedVertexData.uv5s;
  39039. if (uv5s) {
  39040. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39041. }
  39042. // uv6s
  39043. var uv6s = parsedVertexData.uv6s;
  39044. if (uv6s) {
  39045. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39046. }
  39047. // colors
  39048. var colors = parsedVertexData.colors;
  39049. if (colors) {
  39050. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39051. }
  39052. // matricesIndices
  39053. var matricesIndices = parsedVertexData.matricesIndices;
  39054. if (matricesIndices) {
  39055. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39056. }
  39057. // matricesWeights
  39058. var matricesWeights = parsedVertexData.matricesWeights;
  39059. if (matricesWeights) {
  39060. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39061. }
  39062. // indices
  39063. var indices = parsedVertexData.indices;
  39064. if (indices) {
  39065. vertexData.indices = indices;
  39066. }
  39067. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39068. };
  39069. return VertexData;
  39070. }());
  39071. BABYLON.VertexData = VertexData;
  39072. })(BABYLON || (BABYLON = {}));
  39073. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39074. var BABYLON;
  39075. (function (BABYLON) {
  39076. /**
  39077. * Class used to store geometry data (vertex buffers + index buffer)
  39078. */
  39079. var Geometry = /** @class */ (function () {
  39080. /**
  39081. * Creates a new geometry
  39082. * @param id defines the unique ID
  39083. * @param scene defines the hosting scene
  39084. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39085. * @param updatable defines if geometry must be updatable (false by default)
  39086. * @param mesh defines the mesh that will be associated with the geometry
  39087. */
  39088. function Geometry(id, scene, vertexData, updatable, mesh) {
  39089. if (updatable === void 0) { updatable = false; }
  39090. if (mesh === void 0) { mesh = null; }
  39091. /**
  39092. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39093. */
  39094. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39095. this._totalVertices = 0;
  39096. this._isDisposed = false;
  39097. this._indexBufferIsUpdatable = false;
  39098. this.id = id;
  39099. this._engine = scene.getEngine();
  39100. this._meshes = [];
  39101. this._scene = scene;
  39102. //Init vertex buffer cache
  39103. this._vertexBuffers = {};
  39104. this._indices = [];
  39105. this._updatable = updatable;
  39106. // vertexData
  39107. if (vertexData) {
  39108. this.setAllVerticesData(vertexData, updatable);
  39109. }
  39110. else {
  39111. this._totalVertices = 0;
  39112. this._indices = [];
  39113. }
  39114. if (this._engine.getCaps().vertexArrayObject) {
  39115. this._vertexArrayObjects = {};
  39116. }
  39117. // applyToMesh
  39118. if (mesh) {
  39119. if (mesh.getClassName() === "LinesMesh") {
  39120. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39121. this._updateExtend();
  39122. }
  39123. this.applyToMesh(mesh);
  39124. mesh.computeWorldMatrix(true);
  39125. }
  39126. }
  39127. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39128. /**
  39129. * 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
  39130. */
  39131. get: function () {
  39132. return this._boundingBias;
  39133. },
  39134. /**
  39135. * 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
  39136. */
  39137. set: function (value) {
  39138. if (this._boundingBias && this._boundingBias.equals(value)) {
  39139. return;
  39140. }
  39141. this._boundingBias = value.clone();
  39142. this._updateBoundingInfo(true, null);
  39143. },
  39144. enumerable: true,
  39145. configurable: true
  39146. });
  39147. /**
  39148. * Static function used to attach a new empty geometry to a mesh
  39149. * @param mesh defines the mesh to attach the geometry to
  39150. * @returns the new {BABYLON.Geometry}
  39151. */
  39152. Geometry.CreateGeometryForMesh = function (mesh) {
  39153. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39154. geometry.applyToMesh(mesh);
  39155. return geometry;
  39156. };
  39157. Object.defineProperty(Geometry.prototype, "extend", {
  39158. /**
  39159. * Gets the current extend of the geometry
  39160. */
  39161. get: function () {
  39162. return this._extend;
  39163. },
  39164. enumerable: true,
  39165. configurable: true
  39166. });
  39167. /**
  39168. * Gets the hosting scene
  39169. * @returns the hosting {BABYLON.Scene}
  39170. */
  39171. Geometry.prototype.getScene = function () {
  39172. return this._scene;
  39173. };
  39174. /**
  39175. * Gets the hosting engine
  39176. * @returns the hosting {BABYLON.Engine}
  39177. */
  39178. Geometry.prototype.getEngine = function () {
  39179. return this._engine;
  39180. };
  39181. /**
  39182. * Defines if the geometry is ready to use
  39183. * @returns true if the geometry is ready to be used
  39184. */
  39185. Geometry.prototype.isReady = function () {
  39186. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39187. };
  39188. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39189. /**
  39190. * Gets a value indicating that the geometry should not be serialized
  39191. */
  39192. get: function () {
  39193. for (var index = 0; index < this._meshes.length; index++) {
  39194. if (!this._meshes[index].doNotSerialize) {
  39195. return false;
  39196. }
  39197. }
  39198. return true;
  39199. },
  39200. enumerable: true,
  39201. configurable: true
  39202. });
  39203. /** @hidden */
  39204. Geometry.prototype._rebuild = function () {
  39205. if (this._vertexArrayObjects) {
  39206. this._vertexArrayObjects = {};
  39207. }
  39208. // Index buffer
  39209. if (this._meshes.length !== 0 && this._indices) {
  39210. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39211. }
  39212. // Vertex buffers
  39213. for (var key in this._vertexBuffers) {
  39214. var vertexBuffer = this._vertexBuffers[key];
  39215. vertexBuffer._rebuild();
  39216. }
  39217. };
  39218. /**
  39219. * Affects all geometry data in one call
  39220. * @param vertexData defines the geometry data
  39221. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39222. */
  39223. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39224. vertexData.applyToGeometry(this, updatable);
  39225. this.notifyUpdate();
  39226. };
  39227. /**
  39228. * Set specific vertex data
  39229. * @param kind defines the data kind (Position, normal, etc...)
  39230. * @param data defines the vertex data to use
  39231. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39232. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39233. */
  39234. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39235. if (updatable === void 0) { updatable = false; }
  39236. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39237. this.setVerticesBuffer(buffer);
  39238. };
  39239. /**
  39240. * Removes a specific vertex data
  39241. * @param kind defines the data kind (Position, normal, etc...)
  39242. */
  39243. Geometry.prototype.removeVerticesData = function (kind) {
  39244. if (this._vertexBuffers[kind]) {
  39245. this._vertexBuffers[kind].dispose();
  39246. delete this._vertexBuffers[kind];
  39247. }
  39248. };
  39249. /**
  39250. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39251. * @param buffer defines the vertex buffer to use
  39252. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39253. */
  39254. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39255. if (totalVertices === void 0) { totalVertices = null; }
  39256. var kind = buffer.getKind();
  39257. if (this._vertexBuffers[kind]) {
  39258. this._vertexBuffers[kind].dispose();
  39259. }
  39260. this._vertexBuffers[kind] = buffer;
  39261. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39262. var data = buffer.getData();
  39263. if (totalVertices != null) {
  39264. this._totalVertices = totalVertices;
  39265. }
  39266. else {
  39267. if (data != null) {
  39268. this._totalVertices = data.length / (buffer.byteStride / 4);
  39269. }
  39270. }
  39271. this._updateExtend(data);
  39272. this._resetPointsArrayCache();
  39273. var meshes = this._meshes;
  39274. var numOfMeshes = meshes.length;
  39275. for (var index = 0; index < numOfMeshes; index++) {
  39276. var mesh = meshes[index];
  39277. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39278. mesh._createGlobalSubMesh(false);
  39279. mesh.computeWorldMatrix(true);
  39280. }
  39281. }
  39282. this.notifyUpdate(kind);
  39283. if (this._vertexArrayObjects) {
  39284. this._disposeVertexArrayObjects();
  39285. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39286. }
  39287. };
  39288. /**
  39289. * Update a specific vertex buffer
  39290. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39291. * It will do nothing if the buffer is not updatable
  39292. * @param kind defines the data kind (Position, normal, etc...)
  39293. * @param data defines the data to use
  39294. * @param offset defines the offset in the target buffer where to store the data
  39295. * @param useBytes set to true if the offset is in bytes
  39296. */
  39297. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39298. if (useBytes === void 0) { useBytes = false; }
  39299. var vertexBuffer = this.getVertexBuffer(kind);
  39300. if (!vertexBuffer) {
  39301. return;
  39302. }
  39303. vertexBuffer.updateDirectly(data, offset, useBytes);
  39304. this.notifyUpdate(kind);
  39305. };
  39306. /**
  39307. * Update a specific vertex buffer
  39308. * This function will create a new buffer if the current one is not updatable
  39309. * @param kind defines the data kind (Position, normal, etc...)
  39310. * @param data defines the data to use
  39311. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39312. */
  39313. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39314. if (updateExtends === void 0) { updateExtends = false; }
  39315. var vertexBuffer = this.getVertexBuffer(kind);
  39316. if (!vertexBuffer) {
  39317. return;
  39318. }
  39319. vertexBuffer.update(data);
  39320. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39321. this._updateBoundingInfo(updateExtends, data);
  39322. }
  39323. this.notifyUpdate(kind);
  39324. };
  39325. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39326. if (updateExtends) {
  39327. this._updateExtend(data);
  39328. }
  39329. var meshes = this._meshes;
  39330. var numOfMeshes = meshes.length;
  39331. this._resetPointsArrayCache();
  39332. for (var index = 0; index < numOfMeshes; index++) {
  39333. var mesh = meshes[index];
  39334. if (updateExtends) {
  39335. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39336. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39337. var subMesh = mesh.subMeshes[subIndex];
  39338. subMesh.refreshBoundingInfo();
  39339. }
  39340. }
  39341. }
  39342. };
  39343. /** @hidden */
  39344. Geometry.prototype._bind = function (effect, indexToBind) {
  39345. if (!effect) {
  39346. return;
  39347. }
  39348. if (indexToBind === undefined) {
  39349. indexToBind = this._indexBuffer;
  39350. }
  39351. var vbs = this.getVertexBuffers();
  39352. if (!vbs) {
  39353. return;
  39354. }
  39355. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39356. this._engine.bindBuffers(vbs, indexToBind, effect);
  39357. return;
  39358. }
  39359. // Using VAO
  39360. if (!this._vertexArrayObjects[effect.key]) {
  39361. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39362. }
  39363. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39364. };
  39365. /**
  39366. * Gets total number of vertices
  39367. * @returns the total number of vertices
  39368. */
  39369. Geometry.prototype.getTotalVertices = function () {
  39370. if (!this.isReady()) {
  39371. return 0;
  39372. }
  39373. return this._totalVertices;
  39374. };
  39375. /**
  39376. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39377. * @param kind defines the data kind (Position, normal, etc...)
  39378. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39379. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39380. * @returns a float array containing vertex data
  39381. */
  39382. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39383. var vertexBuffer = this.getVertexBuffer(kind);
  39384. if (!vertexBuffer) {
  39385. return null;
  39386. }
  39387. var data = vertexBuffer.getData();
  39388. if (!data) {
  39389. return null;
  39390. }
  39391. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39392. var count = this._totalVertices * vertexBuffer.getSize();
  39393. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39394. var copy_1 = new Array(count);
  39395. vertexBuffer.forEach(count, function (value, index) {
  39396. copy_1[index] = value;
  39397. });
  39398. return copy_1;
  39399. }
  39400. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39401. if (data instanceof Array) {
  39402. var offset = vertexBuffer.byteOffset / 4;
  39403. return BABYLON.Tools.Slice(data, offset, offset + count);
  39404. }
  39405. else if (data instanceof ArrayBuffer) {
  39406. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39407. }
  39408. else {
  39409. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39410. }
  39411. }
  39412. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39413. return BABYLON.Tools.Slice(data);
  39414. }
  39415. return data;
  39416. };
  39417. /**
  39418. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39419. * @param kind defines the data kind (Position, normal, etc...)
  39420. * @returns true if the vertex buffer with the specified kind is updatable
  39421. */
  39422. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39423. var vb = this._vertexBuffers[kind];
  39424. if (!vb) {
  39425. return false;
  39426. }
  39427. return vb.isUpdatable();
  39428. };
  39429. /**
  39430. * Gets a specific vertex buffer
  39431. * @param kind defines the data kind (Position, normal, etc...)
  39432. * @returns a {BABYLON.VertexBuffer}
  39433. */
  39434. Geometry.prototype.getVertexBuffer = function (kind) {
  39435. if (!this.isReady()) {
  39436. return null;
  39437. }
  39438. return this._vertexBuffers[kind];
  39439. };
  39440. /**
  39441. * Returns all vertex buffers
  39442. * @return an object holding all vertex buffers indexed by kind
  39443. */
  39444. Geometry.prototype.getVertexBuffers = function () {
  39445. if (!this.isReady()) {
  39446. return null;
  39447. }
  39448. return this._vertexBuffers;
  39449. };
  39450. /**
  39451. * Gets a boolean indicating if specific vertex buffer is present
  39452. * @param kind defines the data kind (Position, normal, etc...)
  39453. * @returns true if data is present
  39454. */
  39455. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39456. if (!this._vertexBuffers) {
  39457. if (this._delayInfo) {
  39458. return this._delayInfo.indexOf(kind) !== -1;
  39459. }
  39460. return false;
  39461. }
  39462. return this._vertexBuffers[kind] !== undefined;
  39463. };
  39464. /**
  39465. * Gets a list of all attached data kinds (Position, normal, etc...)
  39466. * @returns a list of string containing all kinds
  39467. */
  39468. Geometry.prototype.getVerticesDataKinds = function () {
  39469. var result = [];
  39470. var kind;
  39471. if (!this._vertexBuffers && this._delayInfo) {
  39472. for (kind in this._delayInfo) {
  39473. result.push(kind);
  39474. }
  39475. }
  39476. else {
  39477. for (kind in this._vertexBuffers) {
  39478. result.push(kind);
  39479. }
  39480. }
  39481. return result;
  39482. };
  39483. /**
  39484. * Update index buffer
  39485. * @param indices defines the indices to store in the index buffer
  39486. * @param offset defines the offset in the target buffer where to store the data
  39487. */
  39488. Geometry.prototype.updateIndices = function (indices, offset) {
  39489. if (!this._indexBuffer) {
  39490. return;
  39491. }
  39492. if (!this._indexBufferIsUpdatable) {
  39493. this.setIndices(indices, null, true);
  39494. }
  39495. else {
  39496. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39497. }
  39498. };
  39499. /**
  39500. * Creates a new index buffer
  39501. * @param indices defines the indices to store in the index buffer
  39502. * @param totalVertices defines the total number of vertices (could be null)
  39503. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39504. */
  39505. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39506. if (totalVertices === void 0) { totalVertices = null; }
  39507. if (updatable === void 0) { updatable = false; }
  39508. if (this._indexBuffer) {
  39509. this._engine._releaseBuffer(this._indexBuffer);
  39510. }
  39511. this._disposeVertexArrayObjects();
  39512. this._indices = indices;
  39513. this._indexBufferIsUpdatable = updatable;
  39514. if (this._meshes.length !== 0 && this._indices) {
  39515. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39516. }
  39517. if (totalVertices != undefined) { // including null and undefined
  39518. this._totalVertices = totalVertices;
  39519. }
  39520. var meshes = this._meshes;
  39521. var numOfMeshes = meshes.length;
  39522. for (var index = 0; index < numOfMeshes; index++) {
  39523. meshes[index]._createGlobalSubMesh(true);
  39524. }
  39525. this.notifyUpdate();
  39526. };
  39527. /**
  39528. * Return the total number of indices
  39529. * @returns the total number of indices
  39530. */
  39531. Geometry.prototype.getTotalIndices = function () {
  39532. if (!this.isReady()) {
  39533. return 0;
  39534. }
  39535. return this._indices.length;
  39536. };
  39537. /**
  39538. * Gets the index buffer array
  39539. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39540. * @returns the index buffer array
  39541. */
  39542. Geometry.prototype.getIndices = function (copyWhenShared) {
  39543. if (!this.isReady()) {
  39544. return null;
  39545. }
  39546. var orig = this._indices;
  39547. if (!copyWhenShared || this._meshes.length === 1) {
  39548. return orig;
  39549. }
  39550. else {
  39551. var len = orig.length;
  39552. var copy = [];
  39553. for (var i = 0; i < len; i++) {
  39554. copy.push(orig[i]);
  39555. }
  39556. return copy;
  39557. }
  39558. };
  39559. /**
  39560. * Gets the index buffer
  39561. * @return the index buffer
  39562. */
  39563. Geometry.prototype.getIndexBuffer = function () {
  39564. if (!this.isReady()) {
  39565. return null;
  39566. }
  39567. return this._indexBuffer;
  39568. };
  39569. /** @hidden */
  39570. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39571. if (effect === void 0) { effect = null; }
  39572. if (!effect || !this._vertexArrayObjects) {
  39573. return;
  39574. }
  39575. if (this._vertexArrayObjects[effect.key]) {
  39576. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39577. delete this._vertexArrayObjects[effect.key];
  39578. }
  39579. };
  39580. /**
  39581. * Release the associated resources for a specific mesh
  39582. * @param mesh defines the source mesh
  39583. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39584. */
  39585. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39586. var meshes = this._meshes;
  39587. var index = meshes.indexOf(mesh);
  39588. if (index === -1) {
  39589. return;
  39590. }
  39591. meshes.splice(index, 1);
  39592. mesh._geometry = null;
  39593. if (meshes.length === 0 && shouldDispose) {
  39594. this.dispose();
  39595. }
  39596. };
  39597. /**
  39598. * Apply current geometry to a given mesh
  39599. * @param mesh defines the mesh to apply geometry to
  39600. */
  39601. Geometry.prototype.applyToMesh = function (mesh) {
  39602. if (mesh._geometry === this) {
  39603. return;
  39604. }
  39605. var previousGeometry = mesh._geometry;
  39606. if (previousGeometry) {
  39607. previousGeometry.releaseForMesh(mesh);
  39608. }
  39609. var meshes = this._meshes;
  39610. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39611. mesh._geometry = this;
  39612. this._scene.pushGeometry(this);
  39613. meshes.push(mesh);
  39614. if (this.isReady()) {
  39615. this._applyToMesh(mesh);
  39616. }
  39617. else {
  39618. mesh._boundingInfo = this._boundingInfo;
  39619. }
  39620. };
  39621. Geometry.prototype._updateExtend = function (data) {
  39622. if (data === void 0) { data = null; }
  39623. if (!data) {
  39624. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39625. }
  39626. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39627. };
  39628. Geometry.prototype._applyToMesh = function (mesh) {
  39629. var numOfMeshes = this._meshes.length;
  39630. // vertexBuffers
  39631. for (var kind in this._vertexBuffers) {
  39632. if (numOfMeshes === 1) {
  39633. this._vertexBuffers[kind].create();
  39634. }
  39635. var buffer = this._vertexBuffers[kind].getBuffer();
  39636. if (buffer)
  39637. buffer.references = numOfMeshes;
  39638. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39639. if (!this._extend) {
  39640. this._updateExtend();
  39641. }
  39642. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39643. mesh._createGlobalSubMesh(false);
  39644. //bounding info was just created again, world matrix should be applied again.
  39645. mesh._updateBoundingInfo();
  39646. }
  39647. }
  39648. // indexBuffer
  39649. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39650. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39651. }
  39652. if (this._indexBuffer) {
  39653. this._indexBuffer.references = numOfMeshes;
  39654. }
  39655. };
  39656. Geometry.prototype.notifyUpdate = function (kind) {
  39657. if (this.onGeometryUpdated) {
  39658. this.onGeometryUpdated(this, kind);
  39659. }
  39660. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39661. var mesh = _a[_i];
  39662. mesh._markSubMeshesAsAttributesDirty();
  39663. }
  39664. };
  39665. /**
  39666. * Load the geometry if it was flagged as delay loaded
  39667. * @param scene defines the hosting scene
  39668. * @param onLoaded defines a callback called when the geometry is loaded
  39669. */
  39670. Geometry.prototype.load = function (scene, onLoaded) {
  39671. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39672. return;
  39673. }
  39674. if (this.isReady()) {
  39675. if (onLoaded) {
  39676. onLoaded();
  39677. }
  39678. return;
  39679. }
  39680. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39681. this._queueLoad(scene, onLoaded);
  39682. };
  39683. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39684. var _this = this;
  39685. if (!this.delayLoadingFile) {
  39686. return;
  39687. }
  39688. scene._addPendingData(this);
  39689. scene._loadFile(this.delayLoadingFile, function (data) {
  39690. if (!_this._delayLoadingFunction) {
  39691. return;
  39692. }
  39693. _this._delayLoadingFunction(JSON.parse(data), _this);
  39694. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39695. _this._delayInfo = [];
  39696. scene._removePendingData(_this);
  39697. var meshes = _this._meshes;
  39698. var numOfMeshes = meshes.length;
  39699. for (var index = 0; index < numOfMeshes; index++) {
  39700. _this._applyToMesh(meshes[index]);
  39701. }
  39702. if (onLoaded) {
  39703. onLoaded();
  39704. }
  39705. }, undefined, true);
  39706. };
  39707. /**
  39708. * Invert the geometry to move from a right handed system to a left handed one.
  39709. */
  39710. Geometry.prototype.toLeftHanded = function () {
  39711. // Flip faces
  39712. var tIndices = this.getIndices(false);
  39713. if (tIndices != null && tIndices.length > 0) {
  39714. for (var i = 0; i < tIndices.length; i += 3) {
  39715. var tTemp = tIndices[i + 0];
  39716. tIndices[i + 0] = tIndices[i + 2];
  39717. tIndices[i + 2] = tTemp;
  39718. }
  39719. this.setIndices(tIndices);
  39720. }
  39721. // Negate position.z
  39722. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39723. if (tPositions != null && tPositions.length > 0) {
  39724. for (var i = 0; i < tPositions.length; i += 3) {
  39725. tPositions[i + 2] = -tPositions[i + 2];
  39726. }
  39727. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39728. }
  39729. // Negate normal.z
  39730. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39731. if (tNormals != null && tNormals.length > 0) {
  39732. for (var i = 0; i < tNormals.length; i += 3) {
  39733. tNormals[i + 2] = -tNormals[i + 2];
  39734. }
  39735. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39736. }
  39737. };
  39738. // Cache
  39739. /** @hidden */
  39740. Geometry.prototype._resetPointsArrayCache = function () {
  39741. this._positions = null;
  39742. };
  39743. /** @hidden */
  39744. Geometry.prototype._generatePointsArray = function () {
  39745. if (this._positions)
  39746. return true;
  39747. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39748. if (!data || data.length === 0) {
  39749. return false;
  39750. }
  39751. this._positions = [];
  39752. for (var index = 0; index < data.length; index += 3) {
  39753. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39754. }
  39755. return true;
  39756. };
  39757. /**
  39758. * Gets a value indicating if the geometry is disposed
  39759. * @returns true if the geometry was disposed
  39760. */
  39761. Geometry.prototype.isDisposed = function () {
  39762. return this._isDisposed;
  39763. };
  39764. Geometry.prototype._disposeVertexArrayObjects = function () {
  39765. if (this._vertexArrayObjects) {
  39766. for (var kind in this._vertexArrayObjects) {
  39767. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39768. }
  39769. this._vertexArrayObjects = {};
  39770. }
  39771. };
  39772. /**
  39773. * Free all associated resources
  39774. */
  39775. Geometry.prototype.dispose = function () {
  39776. var meshes = this._meshes;
  39777. var numOfMeshes = meshes.length;
  39778. var index;
  39779. for (index = 0; index < numOfMeshes; index++) {
  39780. this.releaseForMesh(meshes[index]);
  39781. }
  39782. this._meshes = [];
  39783. this._disposeVertexArrayObjects();
  39784. for (var kind in this._vertexBuffers) {
  39785. this._vertexBuffers[kind].dispose();
  39786. }
  39787. this._vertexBuffers = {};
  39788. this._totalVertices = 0;
  39789. if (this._indexBuffer) {
  39790. this._engine._releaseBuffer(this._indexBuffer);
  39791. }
  39792. this._indexBuffer = null;
  39793. this._indices = [];
  39794. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39795. this.delayLoadingFile = null;
  39796. this._delayLoadingFunction = null;
  39797. this._delayInfo = [];
  39798. this._boundingInfo = null;
  39799. this._scene.removeGeometry(this);
  39800. this._isDisposed = true;
  39801. };
  39802. /**
  39803. * Clone the current geometry into a new geometry
  39804. * @param id defines the unique ID of the new geometry
  39805. * @returns a new geometry object
  39806. */
  39807. Geometry.prototype.copy = function (id) {
  39808. var vertexData = new BABYLON.VertexData();
  39809. vertexData.indices = [];
  39810. var indices = this.getIndices();
  39811. if (indices) {
  39812. for (var index = 0; index < indices.length; index++) {
  39813. vertexData.indices.push(indices[index]);
  39814. }
  39815. }
  39816. var updatable = false;
  39817. var stopChecking = false;
  39818. var kind;
  39819. for (kind in this._vertexBuffers) {
  39820. // using slice() to make a copy of the array and not just reference it
  39821. var data = this.getVerticesData(kind);
  39822. if (data instanceof Float32Array) {
  39823. vertexData.set(new Float32Array(data), kind);
  39824. }
  39825. else {
  39826. vertexData.set(data.slice(0), kind);
  39827. }
  39828. if (!stopChecking) {
  39829. var vb = this.getVertexBuffer(kind);
  39830. if (vb) {
  39831. updatable = vb.isUpdatable();
  39832. stopChecking = !updatable;
  39833. }
  39834. }
  39835. }
  39836. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39837. geometry.delayLoadState = this.delayLoadState;
  39838. geometry.delayLoadingFile = this.delayLoadingFile;
  39839. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39840. for (kind in this._delayInfo) {
  39841. geometry._delayInfo = geometry._delayInfo || [];
  39842. geometry._delayInfo.push(kind);
  39843. }
  39844. // Bounding info
  39845. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39846. return geometry;
  39847. };
  39848. /**
  39849. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39850. * @return a JSON representation of the current geometry data (without the vertices data)
  39851. */
  39852. Geometry.prototype.serialize = function () {
  39853. var serializationObject = {};
  39854. serializationObject.id = this.id;
  39855. serializationObject.updatable = this._updatable;
  39856. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39857. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39858. }
  39859. return serializationObject;
  39860. };
  39861. Geometry.prototype.toNumberArray = function (origin) {
  39862. if (Array.isArray(origin)) {
  39863. return origin;
  39864. }
  39865. else {
  39866. return Array.prototype.slice.call(origin);
  39867. }
  39868. };
  39869. /**
  39870. * Serialize all vertices data into a JSON oject
  39871. * @returns a JSON representation of the current geometry data
  39872. */
  39873. Geometry.prototype.serializeVerticeData = function () {
  39874. var serializationObject = this.serialize();
  39875. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39876. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39877. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39878. serializationObject.positions._updatable = true;
  39879. }
  39880. }
  39881. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39882. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39883. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39884. serializationObject.normals._updatable = true;
  39885. }
  39886. }
  39887. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39888. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39889. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39890. serializationObject.tangets._updatable = true;
  39891. }
  39892. }
  39893. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39894. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39895. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39896. serializationObject.uvs._updatable = true;
  39897. }
  39898. }
  39899. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39900. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39901. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39902. serializationObject.uv2s._updatable = true;
  39903. }
  39904. }
  39905. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39906. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39907. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39908. serializationObject.uv3s._updatable = true;
  39909. }
  39910. }
  39911. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39912. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39913. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39914. serializationObject.uv4s._updatable = true;
  39915. }
  39916. }
  39917. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39918. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39919. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39920. serializationObject.uv5s._updatable = true;
  39921. }
  39922. }
  39923. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39924. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39925. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39926. serializationObject.uv6s._updatable = true;
  39927. }
  39928. }
  39929. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39930. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39931. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39932. serializationObject.colors._updatable = true;
  39933. }
  39934. }
  39935. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39936. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39937. serializationObject.matricesIndices._isExpanded = true;
  39938. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39939. serializationObject.matricesIndices._updatable = true;
  39940. }
  39941. }
  39942. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39943. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39944. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39945. serializationObject.matricesWeights._updatable = true;
  39946. }
  39947. }
  39948. serializationObject.indices = this.toNumberArray(this.getIndices());
  39949. return serializationObject;
  39950. };
  39951. // Statics
  39952. /**
  39953. * Extracts a clone of a mesh geometry
  39954. * @param mesh defines the source mesh
  39955. * @param id defines the unique ID of the new geometry object
  39956. * @returns the new geometry object
  39957. */
  39958. Geometry.ExtractFromMesh = function (mesh, id) {
  39959. var geometry = mesh._geometry;
  39960. if (!geometry) {
  39961. return null;
  39962. }
  39963. return geometry.copy(id);
  39964. };
  39965. /**
  39966. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39967. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39968. * Be aware Math.random() could cause collisions, but:
  39969. * "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"
  39970. * @returns a string containing a new GUID
  39971. */
  39972. Geometry.RandomId = function () {
  39973. return BABYLON.Tools.RandomId();
  39974. };
  39975. /** @hidden */
  39976. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39977. var scene = mesh.getScene();
  39978. // Geometry
  39979. var geometryId = parsedGeometry.geometryId;
  39980. if (geometryId) {
  39981. var geometry = scene.getGeometryByID(geometryId);
  39982. if (geometry) {
  39983. geometry.applyToMesh(mesh);
  39984. }
  39985. }
  39986. else if (parsedGeometry instanceof ArrayBuffer) {
  39987. var binaryInfo = mesh._binaryInfo;
  39988. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39989. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39990. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39991. }
  39992. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39993. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39994. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39995. }
  39996. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39997. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39998. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39999. }
  40000. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40001. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40002. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40003. }
  40004. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40005. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40006. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40007. }
  40008. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40009. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40010. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40011. }
  40012. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40013. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40014. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40015. }
  40016. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40017. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40018. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40019. }
  40020. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40021. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40022. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40023. }
  40024. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40025. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40026. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40027. }
  40028. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40029. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40030. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  40031. }
  40032. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40033. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40034. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40035. }
  40036. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40037. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40038. mesh.setIndices(indicesData, null);
  40039. }
  40040. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40041. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40042. mesh.subMeshes = [];
  40043. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40044. var materialIndex = subMeshesData[(i * 5) + 0];
  40045. var verticesStart = subMeshesData[(i * 5) + 1];
  40046. var verticesCount = subMeshesData[(i * 5) + 2];
  40047. var indexStart = subMeshesData[(i * 5) + 3];
  40048. var indexCount = subMeshesData[(i * 5) + 4];
  40049. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40050. }
  40051. }
  40052. }
  40053. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40054. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40055. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40056. if (parsedGeometry.tangents) {
  40057. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40058. }
  40059. if (parsedGeometry.uvs) {
  40060. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40061. }
  40062. if (parsedGeometry.uvs2) {
  40063. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40064. }
  40065. if (parsedGeometry.uvs3) {
  40066. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40067. }
  40068. if (parsedGeometry.uvs4) {
  40069. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40070. }
  40071. if (parsedGeometry.uvs5) {
  40072. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40073. }
  40074. if (parsedGeometry.uvs6) {
  40075. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40076. }
  40077. if (parsedGeometry.colors) {
  40078. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40079. }
  40080. if (parsedGeometry.matricesIndices) {
  40081. if (!parsedGeometry.matricesIndices._isExpanded) {
  40082. var floatIndices = [];
  40083. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40084. var matricesIndex = parsedGeometry.matricesIndices[i];
  40085. floatIndices.push(matricesIndex & 0x000000FF);
  40086. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40087. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40088. floatIndices.push(matricesIndex >> 24);
  40089. }
  40090. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40091. }
  40092. else {
  40093. delete parsedGeometry.matricesIndices._isExpanded;
  40094. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40095. }
  40096. }
  40097. if (parsedGeometry.matricesIndicesExtra) {
  40098. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40099. var floatIndices = [];
  40100. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40101. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40102. floatIndices.push(matricesIndex & 0x000000FF);
  40103. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40104. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40105. floatIndices.push(matricesIndex >> 24);
  40106. }
  40107. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40108. }
  40109. else {
  40110. delete parsedGeometry.matricesIndices._isExpanded;
  40111. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40112. }
  40113. }
  40114. if (parsedGeometry.matricesWeights) {
  40115. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40116. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40117. }
  40118. if (parsedGeometry.matricesWeightsExtra) {
  40119. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40120. }
  40121. mesh.setIndices(parsedGeometry.indices, null);
  40122. }
  40123. // SubMeshes
  40124. if (parsedGeometry.subMeshes) {
  40125. mesh.subMeshes = [];
  40126. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40127. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40128. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40129. }
  40130. }
  40131. // Flat shading
  40132. if (mesh._shouldGenerateFlatShading) {
  40133. mesh.convertToFlatShadedMesh();
  40134. delete mesh._shouldGenerateFlatShading;
  40135. }
  40136. // Update
  40137. mesh.computeWorldMatrix(true);
  40138. // Octree
  40139. var sceneOctree = scene.selectionOctree;
  40140. if (sceneOctree !== undefined && sceneOctree !== null) {
  40141. sceneOctree.addMesh(mesh);
  40142. }
  40143. };
  40144. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40145. var epsilon = 1e-3;
  40146. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40147. return;
  40148. }
  40149. var noInfluenceBoneIndex = 0.0;
  40150. if (parsedGeometry.skeletonId > -1) {
  40151. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40152. if (!skeleton) {
  40153. return;
  40154. }
  40155. noInfluenceBoneIndex = skeleton.bones.length;
  40156. }
  40157. else {
  40158. return;
  40159. }
  40160. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40161. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40162. var matricesWeights = parsedGeometry.matricesWeights;
  40163. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40164. var influencers = parsedGeometry.numBoneInfluencer;
  40165. var size = matricesWeights.length;
  40166. for (var i = 0; i < size; i += 4) {
  40167. var weight = 0.0;
  40168. var firstZeroWeight = -1;
  40169. for (var j = 0; j < 4; j++) {
  40170. var w = matricesWeights[i + j];
  40171. weight += w;
  40172. if (w < epsilon && firstZeroWeight < 0) {
  40173. firstZeroWeight = j;
  40174. }
  40175. }
  40176. if (matricesWeightsExtra) {
  40177. for (var j = 0; j < 4; j++) {
  40178. var w = matricesWeightsExtra[i + j];
  40179. weight += w;
  40180. if (w < epsilon && firstZeroWeight < 0) {
  40181. firstZeroWeight = j + 4;
  40182. }
  40183. }
  40184. }
  40185. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40186. firstZeroWeight = influencers - 1;
  40187. }
  40188. if (weight > epsilon) {
  40189. var mweight = 1.0 / weight;
  40190. for (var j = 0; j < 4; j++) {
  40191. matricesWeights[i + j] *= mweight;
  40192. }
  40193. if (matricesWeightsExtra) {
  40194. for (var j = 0; j < 4; j++) {
  40195. matricesWeightsExtra[i + j] *= mweight;
  40196. }
  40197. }
  40198. }
  40199. else {
  40200. if (firstZeroWeight >= 4) {
  40201. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40202. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40203. }
  40204. else {
  40205. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40206. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40207. }
  40208. }
  40209. }
  40210. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40211. if (parsedGeometry.matricesWeightsExtra) {
  40212. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40213. }
  40214. };
  40215. /**
  40216. * Create a new geometry from persisted data (Using .babylon file format)
  40217. * @param parsedVertexData defines the persisted data
  40218. * @param scene defines the hosting scene
  40219. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40220. * @returns the new geometry object
  40221. */
  40222. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40223. if (scene.getGeometryByID(parsedVertexData.id)) {
  40224. return null; // null since geometry could be something else than a box...
  40225. }
  40226. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40227. if (BABYLON.Tags) {
  40228. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40229. }
  40230. if (parsedVertexData.delayLoadingFile) {
  40231. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40232. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40233. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40234. geometry._delayInfo = [];
  40235. if (parsedVertexData.hasUVs) {
  40236. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40237. }
  40238. if (parsedVertexData.hasUVs2) {
  40239. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40240. }
  40241. if (parsedVertexData.hasUVs3) {
  40242. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40243. }
  40244. if (parsedVertexData.hasUVs4) {
  40245. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40246. }
  40247. if (parsedVertexData.hasUVs5) {
  40248. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40249. }
  40250. if (parsedVertexData.hasUVs6) {
  40251. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40252. }
  40253. if (parsedVertexData.hasColors) {
  40254. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40255. }
  40256. if (parsedVertexData.hasMatricesIndices) {
  40257. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40258. }
  40259. if (parsedVertexData.hasMatricesWeights) {
  40260. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40261. }
  40262. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40263. }
  40264. else {
  40265. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40266. }
  40267. scene.pushGeometry(geometry, true);
  40268. return geometry;
  40269. };
  40270. return Geometry;
  40271. }());
  40272. BABYLON.Geometry = Geometry;
  40273. // Primitives
  40274. /// Abstract class
  40275. /**
  40276. * Abstract class used to provide common services for all typed geometries
  40277. * @hidden
  40278. */
  40279. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40280. __extends(_PrimitiveGeometry, _super);
  40281. /**
  40282. * Creates a new typed geometry
  40283. * @param id defines the unique ID of the geometry
  40284. * @param scene defines the hosting scene
  40285. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40286. * @param mesh defines the hosting mesh (can be null)
  40287. */
  40288. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40289. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40290. if (mesh === void 0) { mesh = null; }
  40291. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40292. _this._canBeRegenerated = _canBeRegenerated;
  40293. _this._beingRegenerated = true;
  40294. _this.regenerate();
  40295. _this._beingRegenerated = false;
  40296. return _this;
  40297. }
  40298. /**
  40299. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40300. * @returns true if the geometry can be regenerated
  40301. */
  40302. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40303. return this._canBeRegenerated;
  40304. };
  40305. /**
  40306. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40307. */
  40308. _PrimitiveGeometry.prototype.regenerate = function () {
  40309. if (!this._canBeRegenerated) {
  40310. return;
  40311. }
  40312. this._beingRegenerated = true;
  40313. this.setAllVerticesData(this._regenerateVertexData(), false);
  40314. this._beingRegenerated = false;
  40315. };
  40316. /**
  40317. * Clone the geometry
  40318. * @param id defines the unique ID of the new geometry
  40319. * @returns the new geometry
  40320. */
  40321. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40322. return _super.prototype.copy.call(this, id);
  40323. };
  40324. // overrides
  40325. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40326. if (!this._beingRegenerated) {
  40327. return;
  40328. }
  40329. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40330. };
  40331. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40332. if (!this._beingRegenerated) {
  40333. return;
  40334. }
  40335. _super.prototype.setVerticesData.call(this, kind, data, false);
  40336. };
  40337. // to override
  40338. /** @hidden */
  40339. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40340. throw new Error("Abstract method");
  40341. };
  40342. _PrimitiveGeometry.prototype.copy = function (id) {
  40343. throw new Error("Must be overriden in sub-classes.");
  40344. };
  40345. _PrimitiveGeometry.prototype.serialize = function () {
  40346. var serializationObject = _super.prototype.serialize.call(this);
  40347. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40348. return serializationObject;
  40349. };
  40350. return _PrimitiveGeometry;
  40351. }(Geometry));
  40352. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40353. /**
  40354. * Creates a ribbon geometry
  40355. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40356. */
  40357. var RibbonGeometry = /** @class */ (function (_super) {
  40358. __extends(RibbonGeometry, _super);
  40359. /**
  40360. * Creates a ribbon geometry
  40361. * @param id defines the unique ID of the geometry
  40362. * @param scene defines the hosting scene
  40363. * @param pathArray defines the array of paths to use
  40364. * @param closeArray defines if the last path and the first path must be joined
  40365. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40366. * @param offset defines the offset between points
  40367. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40368. * @param mesh defines the hosting mesh (can be null)
  40369. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40370. */
  40371. function RibbonGeometry(id, scene,
  40372. /**
  40373. * Defines the array of paths to use
  40374. */
  40375. pathArray,
  40376. /**
  40377. * Defines if the last and first points of each path in your pathArray must be joined
  40378. */
  40379. closeArray,
  40380. /**
  40381. * Defines if the last and first points of each path in your pathArray must be joined
  40382. */
  40383. closePath,
  40384. /**
  40385. * Defines the offset between points
  40386. */
  40387. offset, canBeRegenerated, mesh,
  40388. /**
  40389. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40390. */
  40391. side) {
  40392. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40393. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40394. _this.pathArray = pathArray;
  40395. _this.closeArray = closeArray;
  40396. _this.closePath = closePath;
  40397. _this.offset = offset;
  40398. _this.side = side;
  40399. return _this;
  40400. }
  40401. /** @hidden */
  40402. RibbonGeometry.prototype._regenerateVertexData = function () {
  40403. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40404. };
  40405. RibbonGeometry.prototype.copy = function (id) {
  40406. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40407. };
  40408. return RibbonGeometry;
  40409. }(_PrimitiveGeometry));
  40410. BABYLON.RibbonGeometry = RibbonGeometry;
  40411. /**
  40412. * Creates a box geometry
  40413. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40414. */
  40415. var BoxGeometry = /** @class */ (function (_super) {
  40416. __extends(BoxGeometry, _super);
  40417. /**
  40418. * Creates a box geometry
  40419. * @param id defines the unique ID of the geometry
  40420. * @param scene defines the hosting scene
  40421. * @param size defines the zise of the box (width, height and depth are the same)
  40422. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40423. * @param mesh defines the hosting mesh (can be null)
  40424. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40425. */
  40426. function BoxGeometry(id, scene,
  40427. /**
  40428. * Defines the zise of the box (width, height and depth are the same)
  40429. */
  40430. size, canBeRegenerated, mesh,
  40431. /**
  40432. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40433. */
  40434. side) {
  40435. if (mesh === void 0) { mesh = null; }
  40436. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40437. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40438. _this.size = size;
  40439. _this.side = side;
  40440. return _this;
  40441. }
  40442. BoxGeometry.prototype._regenerateVertexData = function () {
  40443. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40444. };
  40445. BoxGeometry.prototype.copy = function (id) {
  40446. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40447. };
  40448. BoxGeometry.prototype.serialize = function () {
  40449. var serializationObject = _super.prototype.serialize.call(this);
  40450. serializationObject.size = this.size;
  40451. return serializationObject;
  40452. };
  40453. BoxGeometry.Parse = function (parsedBox, scene) {
  40454. if (scene.getGeometryByID(parsedBox.id)) {
  40455. return null; // null since geometry could be something else than a box...
  40456. }
  40457. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40458. if (BABYLON.Tags) {
  40459. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40460. }
  40461. scene.pushGeometry(box, true);
  40462. return box;
  40463. };
  40464. return BoxGeometry;
  40465. }(_PrimitiveGeometry));
  40466. BABYLON.BoxGeometry = BoxGeometry;
  40467. /**
  40468. * Creates a sphere geometry
  40469. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40470. */
  40471. var SphereGeometry = /** @class */ (function (_super) {
  40472. __extends(SphereGeometry, _super);
  40473. /**
  40474. * Create a new sphere geometry
  40475. * @param id defines the unique ID of the geometry
  40476. * @param scene defines the hosting scene
  40477. * @param segments defines the number of segments to use to create the sphere
  40478. * @param diameter defines the diameter of the sphere
  40479. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40480. * @param mesh defines the hosting mesh (can be null)
  40481. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40482. */
  40483. function SphereGeometry(id, scene,
  40484. /**
  40485. * Defines the number of segments to use to create the sphere
  40486. */
  40487. segments,
  40488. /**
  40489. * Defines the diameter of the sphere
  40490. */
  40491. diameter, 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.segments = segments;
  40500. _this.diameter = diameter;
  40501. _this.side = side;
  40502. return _this;
  40503. }
  40504. SphereGeometry.prototype._regenerateVertexData = function () {
  40505. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40506. };
  40507. SphereGeometry.prototype.copy = function (id) {
  40508. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40509. };
  40510. SphereGeometry.prototype.serialize = function () {
  40511. var serializationObject = _super.prototype.serialize.call(this);
  40512. serializationObject.segments = this.segments;
  40513. serializationObject.diameter = this.diameter;
  40514. return serializationObject;
  40515. };
  40516. SphereGeometry.Parse = function (parsedSphere, scene) {
  40517. if (scene.getGeometryByID(parsedSphere.id)) {
  40518. return null; // null since geometry could be something else than a sphere...
  40519. }
  40520. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40521. if (BABYLON.Tags) {
  40522. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40523. }
  40524. scene.pushGeometry(sphere, true);
  40525. return sphere;
  40526. };
  40527. return SphereGeometry;
  40528. }(_PrimitiveGeometry));
  40529. BABYLON.SphereGeometry = SphereGeometry;
  40530. /**
  40531. * Creates a disc geometry
  40532. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40533. */
  40534. var DiscGeometry = /** @class */ (function (_super) {
  40535. __extends(DiscGeometry, _super);
  40536. /**
  40537. * Creates a new disc geometry
  40538. * @param id defines the unique ID of the geometry
  40539. * @param scene defines the hosting scene
  40540. * @param radius defines the radius of the disc
  40541. * @param tessellation defines the tesselation factor to apply to the disc
  40542. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40543. * @param mesh defines the hosting mesh (can be null)
  40544. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40545. */
  40546. function DiscGeometry(id, scene,
  40547. /**
  40548. * Defines the radius of the disc
  40549. */
  40550. radius,
  40551. /**
  40552. * Defines the tesselation factor to apply to the disc
  40553. */
  40554. tessellation, canBeRegenerated, mesh,
  40555. /**
  40556. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40557. */
  40558. side) {
  40559. if (mesh === void 0) { mesh = null; }
  40560. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40561. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40562. _this.radius = radius;
  40563. _this.tessellation = tessellation;
  40564. _this.side = side;
  40565. return _this;
  40566. }
  40567. DiscGeometry.prototype._regenerateVertexData = function () {
  40568. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40569. };
  40570. DiscGeometry.prototype.copy = function (id) {
  40571. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40572. };
  40573. return DiscGeometry;
  40574. }(_PrimitiveGeometry));
  40575. BABYLON.DiscGeometry = DiscGeometry;
  40576. /**
  40577. * Creates a new cylinder geometry
  40578. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40579. */
  40580. var CylinderGeometry = /** @class */ (function (_super) {
  40581. __extends(CylinderGeometry, _super);
  40582. /**
  40583. * Creates a new cylinder geometry
  40584. * @param id defines the unique ID of the geometry
  40585. * @param scene defines the hosting scene
  40586. * @param height defines the height of the cylinder
  40587. * @param diameterTop defines the diameter of the cylinder's top cap
  40588. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40589. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40590. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40591. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40592. * @param mesh defines the hosting mesh (can be null)
  40593. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40594. */
  40595. function CylinderGeometry(id, scene,
  40596. /**
  40597. * Defines the height of the cylinder
  40598. */
  40599. height,
  40600. /**
  40601. * Defines the diameter of the cylinder's top cap
  40602. */
  40603. diameterTop,
  40604. /**
  40605. * Defines the diameter of the cylinder's bottom cap
  40606. */
  40607. diameterBottom,
  40608. /**
  40609. * Defines the tessellation factor to apply to the cylinder
  40610. */
  40611. tessellation,
  40612. /**
  40613. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40614. */
  40615. subdivisions, canBeRegenerated, mesh,
  40616. /**
  40617. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40618. */
  40619. side) {
  40620. if (subdivisions === void 0) { subdivisions = 1; }
  40621. if (mesh === void 0) { mesh = null; }
  40622. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40623. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40624. _this.height = height;
  40625. _this.diameterTop = diameterTop;
  40626. _this.diameterBottom = diameterBottom;
  40627. _this.tessellation = tessellation;
  40628. _this.subdivisions = subdivisions;
  40629. _this.side = side;
  40630. return _this;
  40631. }
  40632. CylinderGeometry.prototype._regenerateVertexData = function () {
  40633. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40634. };
  40635. CylinderGeometry.prototype.copy = function (id) {
  40636. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40637. };
  40638. CylinderGeometry.prototype.serialize = function () {
  40639. var serializationObject = _super.prototype.serialize.call(this);
  40640. serializationObject.height = this.height;
  40641. serializationObject.diameterTop = this.diameterTop;
  40642. serializationObject.diameterBottom = this.diameterBottom;
  40643. serializationObject.tessellation = this.tessellation;
  40644. return serializationObject;
  40645. };
  40646. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40647. if (scene.getGeometryByID(parsedCylinder.id)) {
  40648. return null; // null since geometry could be something else than a cylinder...
  40649. }
  40650. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40651. if (BABYLON.Tags) {
  40652. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40653. }
  40654. scene.pushGeometry(cylinder, true);
  40655. return cylinder;
  40656. };
  40657. return CylinderGeometry;
  40658. }(_PrimitiveGeometry));
  40659. BABYLON.CylinderGeometry = CylinderGeometry;
  40660. /**
  40661. * Creates a new torus geometry
  40662. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40663. */
  40664. var TorusGeometry = /** @class */ (function (_super) {
  40665. __extends(TorusGeometry, _super);
  40666. /**
  40667. * Creates a new torus geometry
  40668. * @param id defines the unique ID of the geometry
  40669. * @param scene defines the hosting scene
  40670. * @param diameter defines the diameter of the torus
  40671. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40672. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40673. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40674. * @param mesh defines the hosting mesh (can be null)
  40675. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40676. */
  40677. function TorusGeometry(id, scene,
  40678. /**
  40679. * Defines the diameter of the torus
  40680. */
  40681. diameter,
  40682. /**
  40683. * Defines the thickness of the torus (ie. internal diameter)
  40684. */
  40685. thickness,
  40686. /**
  40687. * Defines the tesselation factor to apply to the torus
  40688. */
  40689. tessellation, canBeRegenerated, mesh,
  40690. /**
  40691. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40692. */
  40693. side) {
  40694. if (mesh === void 0) { mesh = null; }
  40695. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40696. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40697. _this.diameter = diameter;
  40698. _this.thickness = thickness;
  40699. _this.tessellation = tessellation;
  40700. _this.side = side;
  40701. return _this;
  40702. }
  40703. TorusGeometry.prototype._regenerateVertexData = function () {
  40704. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40705. };
  40706. TorusGeometry.prototype.copy = function (id) {
  40707. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40708. };
  40709. TorusGeometry.prototype.serialize = function () {
  40710. var serializationObject = _super.prototype.serialize.call(this);
  40711. serializationObject.diameter = this.diameter;
  40712. serializationObject.thickness = this.thickness;
  40713. serializationObject.tessellation = this.tessellation;
  40714. return serializationObject;
  40715. };
  40716. TorusGeometry.Parse = function (parsedTorus, scene) {
  40717. if (scene.getGeometryByID(parsedTorus.id)) {
  40718. return null; // null since geometry could be something else than a torus...
  40719. }
  40720. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40721. if (BABYLON.Tags) {
  40722. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40723. }
  40724. scene.pushGeometry(torus, true);
  40725. return torus;
  40726. };
  40727. return TorusGeometry;
  40728. }(_PrimitiveGeometry));
  40729. BABYLON.TorusGeometry = TorusGeometry;
  40730. /**
  40731. * Creates a new ground geometry
  40732. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40733. */
  40734. var GroundGeometry = /** @class */ (function (_super) {
  40735. __extends(GroundGeometry, _super);
  40736. /**
  40737. * Creates a new ground geometry
  40738. * @param id defines the unique ID of the geometry
  40739. * @param scene defines the hosting scene
  40740. * @param width defines the width of the ground
  40741. * @param height defines the height of the ground
  40742. * @param subdivisions defines the subdivisions to apply to the ground
  40743. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40744. * @param mesh defines the hosting mesh (can be null)
  40745. */
  40746. function GroundGeometry(id, scene,
  40747. /**
  40748. * Defines the width of the ground
  40749. */
  40750. width,
  40751. /**
  40752. * Defines the height of the ground
  40753. */
  40754. height,
  40755. /**
  40756. * Defines the subdivisions to apply to the ground
  40757. */
  40758. subdivisions, canBeRegenerated, mesh) {
  40759. if (mesh === void 0) { mesh = null; }
  40760. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40761. _this.width = width;
  40762. _this.height = height;
  40763. _this.subdivisions = subdivisions;
  40764. return _this;
  40765. }
  40766. GroundGeometry.prototype._regenerateVertexData = function () {
  40767. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40768. };
  40769. GroundGeometry.prototype.copy = function (id) {
  40770. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40771. };
  40772. GroundGeometry.prototype.serialize = function () {
  40773. var serializationObject = _super.prototype.serialize.call(this);
  40774. serializationObject.width = this.width;
  40775. serializationObject.height = this.height;
  40776. serializationObject.subdivisions = this.subdivisions;
  40777. return serializationObject;
  40778. };
  40779. GroundGeometry.Parse = function (parsedGround, scene) {
  40780. if (scene.getGeometryByID(parsedGround.id)) {
  40781. return null; // null since geometry could be something else than a ground...
  40782. }
  40783. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40784. if (BABYLON.Tags) {
  40785. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40786. }
  40787. scene.pushGeometry(ground, true);
  40788. return ground;
  40789. };
  40790. return GroundGeometry;
  40791. }(_PrimitiveGeometry));
  40792. BABYLON.GroundGeometry = GroundGeometry;
  40793. /**
  40794. * Creates a tiled ground geometry
  40795. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40796. */
  40797. var TiledGroundGeometry = /** @class */ (function (_super) {
  40798. __extends(TiledGroundGeometry, _super);
  40799. /**
  40800. * Creates a tiled ground geometry
  40801. * @param id defines the unique ID of the geometry
  40802. * @param scene defines the hosting scene
  40803. * @param xmin defines the minimum value on X axis
  40804. * @param zmin defines the minimum value on Z axis
  40805. * @param xmax defines the maximum value on X axis
  40806. * @param zmax defines the maximum value on Z axis
  40807. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40808. * @param precision defines the precision to use when computing the tiles
  40809. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40810. * @param mesh defines the hosting mesh (can be null)
  40811. */
  40812. function TiledGroundGeometry(id, scene,
  40813. /**
  40814. * Defines the minimum value on X axis
  40815. */
  40816. xmin,
  40817. /**
  40818. * Defines the minimum value on Z axis
  40819. */
  40820. zmin,
  40821. /**
  40822. * Defines the maximum value on X axis
  40823. */
  40824. xmax,
  40825. /**
  40826. * Defines the maximum value on Z axis
  40827. */
  40828. zmax,
  40829. /**
  40830. * Defines the subdivisions to apply to the ground
  40831. */
  40832. subdivisions,
  40833. /**
  40834. * Defines the precision to use when computing the tiles
  40835. */
  40836. precision, canBeRegenerated, mesh) {
  40837. if (mesh === void 0) { mesh = null; }
  40838. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40839. _this.xmin = xmin;
  40840. _this.zmin = zmin;
  40841. _this.xmax = xmax;
  40842. _this.zmax = zmax;
  40843. _this.subdivisions = subdivisions;
  40844. _this.precision = precision;
  40845. return _this;
  40846. }
  40847. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40848. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40849. };
  40850. TiledGroundGeometry.prototype.copy = function (id) {
  40851. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40852. };
  40853. return TiledGroundGeometry;
  40854. }(_PrimitiveGeometry));
  40855. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40856. /**
  40857. * Creates a plane geometry
  40858. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40859. */
  40860. var PlaneGeometry = /** @class */ (function (_super) {
  40861. __extends(PlaneGeometry, _super);
  40862. /**
  40863. * Creates a plane geometry
  40864. * @param id defines the unique ID of the geometry
  40865. * @param scene defines the hosting scene
  40866. * @param size defines the size of the plane (width === height)
  40867. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40868. * @param mesh defines the hosting mesh (can be null)
  40869. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40870. */
  40871. function PlaneGeometry(id, scene,
  40872. /**
  40873. * Defines the size of the plane (width === height)
  40874. */
  40875. size, canBeRegenerated, mesh,
  40876. /**
  40877. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40878. */
  40879. side) {
  40880. if (mesh === void 0) { mesh = null; }
  40881. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40882. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40883. _this.size = size;
  40884. _this.side = side;
  40885. return _this;
  40886. }
  40887. PlaneGeometry.prototype._regenerateVertexData = function () {
  40888. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40889. };
  40890. PlaneGeometry.prototype.copy = function (id) {
  40891. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40892. };
  40893. PlaneGeometry.prototype.serialize = function () {
  40894. var serializationObject = _super.prototype.serialize.call(this);
  40895. serializationObject.size = this.size;
  40896. return serializationObject;
  40897. };
  40898. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40899. if (scene.getGeometryByID(parsedPlane.id)) {
  40900. return null; // null since geometry could be something else than a ground...
  40901. }
  40902. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40903. if (BABYLON.Tags) {
  40904. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40905. }
  40906. scene.pushGeometry(plane, true);
  40907. return plane;
  40908. };
  40909. return PlaneGeometry;
  40910. }(_PrimitiveGeometry));
  40911. BABYLON.PlaneGeometry = PlaneGeometry;
  40912. /**
  40913. * Creates a torus knot geometry
  40914. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40915. */
  40916. var TorusKnotGeometry = /** @class */ (function (_super) {
  40917. __extends(TorusKnotGeometry, _super);
  40918. /**
  40919. * Creates a torus knot geometry
  40920. * @param id defines the unique ID of the geometry
  40921. * @param scene defines the hosting scene
  40922. * @param radius defines the radius of the torus knot
  40923. * @param tube defines the thickness of the torus knot tube
  40924. * @param radialSegments defines the number of radial segments
  40925. * @param tubularSegments defines the number of tubular segments
  40926. * @param p defines the first number of windings
  40927. * @param q defines the second number of windings
  40928. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40929. * @param mesh defines the hosting mesh (can be null)
  40930. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40931. */
  40932. function TorusKnotGeometry(id, scene,
  40933. /**
  40934. * Defines the radius of the torus knot
  40935. */
  40936. radius,
  40937. /**
  40938. * Defines the thickness of the torus knot tube
  40939. */
  40940. tube,
  40941. /**
  40942. * Defines the number of radial segments
  40943. */
  40944. radialSegments,
  40945. /**
  40946. * Defines the number of tubular segments
  40947. */
  40948. tubularSegments,
  40949. /**
  40950. * Defines the first number of windings
  40951. */
  40952. p,
  40953. /**
  40954. * Defines the second number of windings
  40955. */
  40956. q, canBeRegenerated, mesh,
  40957. /**
  40958. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40959. */
  40960. side) {
  40961. if (mesh === void 0) { mesh = null; }
  40962. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40963. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40964. _this.radius = radius;
  40965. _this.tube = tube;
  40966. _this.radialSegments = radialSegments;
  40967. _this.tubularSegments = tubularSegments;
  40968. _this.p = p;
  40969. _this.q = q;
  40970. _this.side = side;
  40971. return _this;
  40972. }
  40973. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40974. 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 });
  40975. };
  40976. TorusKnotGeometry.prototype.copy = function (id) {
  40977. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40978. };
  40979. TorusKnotGeometry.prototype.serialize = function () {
  40980. var serializationObject = _super.prototype.serialize.call(this);
  40981. serializationObject.radius = this.radius;
  40982. serializationObject.tube = this.tube;
  40983. serializationObject.radialSegments = this.radialSegments;
  40984. serializationObject.tubularSegments = this.tubularSegments;
  40985. serializationObject.p = this.p;
  40986. serializationObject.q = this.q;
  40987. return serializationObject;
  40988. };
  40989. ;
  40990. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40991. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40992. return null; // null since geometry could be something else than a ground...
  40993. }
  40994. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40995. if (BABYLON.Tags) {
  40996. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40997. }
  40998. scene.pushGeometry(torusKnot, true);
  40999. return torusKnot;
  41000. };
  41001. return TorusKnotGeometry;
  41002. }(_PrimitiveGeometry));
  41003. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41004. //}
  41005. })(BABYLON || (BABYLON = {}));
  41006. //# sourceMappingURL=babylon.geometry.js.map
  41007. var BABYLON;
  41008. (function (BABYLON) {
  41009. /**
  41010. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41011. */
  41012. var PerformanceMonitor = /** @class */ (function () {
  41013. /**
  41014. * constructor
  41015. * @param frameSampleSize The number of samples required to saturate the sliding window
  41016. */
  41017. function PerformanceMonitor(frameSampleSize) {
  41018. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41019. this._enabled = true;
  41020. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41021. }
  41022. /**
  41023. * Samples current frame
  41024. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41025. */
  41026. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41027. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41028. if (!this._enabled)
  41029. return;
  41030. if (this._lastFrameTimeMs != null) {
  41031. var dt = timeMs - this._lastFrameTimeMs;
  41032. this._rollingFrameTime.add(dt);
  41033. }
  41034. this._lastFrameTimeMs = timeMs;
  41035. };
  41036. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41037. /**
  41038. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41039. * @return Average frame time in milliseconds
  41040. */
  41041. get: function () {
  41042. return this._rollingFrameTime.average;
  41043. },
  41044. enumerable: true,
  41045. configurable: true
  41046. });
  41047. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41048. /**
  41049. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41050. * @return Frame time variance in milliseconds squared
  41051. */
  41052. get: function () {
  41053. return this._rollingFrameTime.variance;
  41054. },
  41055. enumerable: true,
  41056. configurable: true
  41057. });
  41058. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41059. /**
  41060. * Returns the frame time of the most recent frame
  41061. * @return Frame time in milliseconds
  41062. */
  41063. get: function () {
  41064. return this._rollingFrameTime.history(0);
  41065. },
  41066. enumerable: true,
  41067. configurable: true
  41068. });
  41069. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41070. /**
  41071. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41072. * @return Framerate in frames per second
  41073. */
  41074. get: function () {
  41075. return 1000.0 / this._rollingFrameTime.average;
  41076. },
  41077. enumerable: true,
  41078. configurable: true
  41079. });
  41080. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41081. /**
  41082. * Returns the average framerate in frames per second using the most recent frame time
  41083. * @return Framerate in frames per second
  41084. */
  41085. get: function () {
  41086. var history = this._rollingFrameTime.history(0);
  41087. if (history === 0) {
  41088. return 0;
  41089. }
  41090. return 1000.0 / history;
  41091. },
  41092. enumerable: true,
  41093. configurable: true
  41094. });
  41095. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41096. /**
  41097. * Returns true if enough samples have been taken to completely fill the sliding window
  41098. * @return true if saturated
  41099. */
  41100. get: function () {
  41101. return this._rollingFrameTime.isSaturated();
  41102. },
  41103. enumerable: true,
  41104. configurable: true
  41105. });
  41106. /**
  41107. * Enables contributions to the sliding window sample set
  41108. */
  41109. PerformanceMonitor.prototype.enable = function () {
  41110. this._enabled = true;
  41111. };
  41112. /**
  41113. * Disables contributions to the sliding window sample set
  41114. * Samples will not be interpolated over the disabled period
  41115. */
  41116. PerformanceMonitor.prototype.disable = function () {
  41117. this._enabled = false;
  41118. //clear last sample to avoid interpolating over the disabled period when next enabled
  41119. this._lastFrameTimeMs = null;
  41120. };
  41121. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41122. /**
  41123. * Returns true if sampling is enabled
  41124. * @return true if enabled
  41125. */
  41126. get: function () {
  41127. return this._enabled;
  41128. },
  41129. enumerable: true,
  41130. configurable: true
  41131. });
  41132. /**
  41133. * Resets performance monitor
  41134. */
  41135. PerformanceMonitor.prototype.reset = function () {
  41136. //clear last sample to avoid interpolating over the disabled period when next enabled
  41137. this._lastFrameTimeMs = null;
  41138. //wipe record
  41139. this._rollingFrameTime.reset();
  41140. };
  41141. return PerformanceMonitor;
  41142. }());
  41143. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41144. /**
  41145. * RollingAverage
  41146. *
  41147. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41148. */
  41149. var RollingAverage = /** @class */ (function () {
  41150. /**
  41151. * constructor
  41152. * @param length The number of samples required to saturate the sliding window
  41153. */
  41154. function RollingAverage(length) {
  41155. this._samples = new Array(length);
  41156. this.reset();
  41157. }
  41158. /**
  41159. * Adds a sample to the sample set
  41160. * @param v The sample value
  41161. */
  41162. RollingAverage.prototype.add = function (v) {
  41163. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41164. var delta;
  41165. //we need to check if we've already wrapped round
  41166. if (this.isSaturated()) {
  41167. //remove bottom of stack from mean
  41168. var bottomValue = this._samples[this._pos];
  41169. delta = bottomValue - this.average;
  41170. this.average -= delta / (this._sampleCount - 1);
  41171. this._m2 -= delta * (bottomValue - this.average);
  41172. }
  41173. else {
  41174. this._sampleCount++;
  41175. }
  41176. //add new value to mean
  41177. delta = v - this.average;
  41178. this.average += delta / (this._sampleCount);
  41179. this._m2 += delta * (v - this.average);
  41180. //set the new variance
  41181. this.variance = this._m2 / (this._sampleCount - 1);
  41182. this._samples[this._pos] = v;
  41183. this._pos++;
  41184. this._pos %= this._samples.length; //positive wrap around
  41185. };
  41186. /**
  41187. * Returns previously added values or null if outside of history or outside the sliding window domain
  41188. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41189. * @return Value previously recorded with add() or null if outside of range
  41190. */
  41191. RollingAverage.prototype.history = function (i) {
  41192. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41193. return 0;
  41194. }
  41195. var i0 = this._wrapPosition(this._pos - 1.0);
  41196. return this._samples[this._wrapPosition(i0 - i)];
  41197. };
  41198. /**
  41199. * Returns true if enough samples have been taken to completely fill the sliding window
  41200. * @return true if sample-set saturated
  41201. */
  41202. RollingAverage.prototype.isSaturated = function () {
  41203. return this._sampleCount >= this._samples.length;
  41204. };
  41205. /**
  41206. * Resets the rolling average (equivalent to 0 samples taken so far)
  41207. */
  41208. RollingAverage.prototype.reset = function () {
  41209. this.average = 0;
  41210. this.variance = 0;
  41211. this._sampleCount = 0;
  41212. this._pos = 0;
  41213. this._m2 = 0;
  41214. };
  41215. /**
  41216. * Wraps a value around the sample range boundaries
  41217. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41218. * @return Wrapped position in sample range
  41219. */
  41220. RollingAverage.prototype._wrapPosition = function (i) {
  41221. var max = this._samples.length;
  41222. return ((i % max) + max) % max;
  41223. };
  41224. return RollingAverage;
  41225. }());
  41226. BABYLON.RollingAverage = RollingAverage;
  41227. })(BABYLON || (BABYLON = {}));
  41228. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41229. var BABYLON;
  41230. (function (BABYLON) {
  41231. /**
  41232. * "Static Class" containing the most commonly used helper while dealing with material for
  41233. * rendering purpose.
  41234. *
  41235. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41236. *
  41237. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41238. */
  41239. var MaterialHelper = /** @class */ (function () {
  41240. function MaterialHelper() {
  41241. }
  41242. /**
  41243. * Bind the current view position to an effect.
  41244. * @param effect The effect to be bound
  41245. * @param scene The scene the eyes position is used from
  41246. */
  41247. MaterialHelper.BindEyePosition = function (effect, scene) {
  41248. if (scene._forcedViewPosition) {
  41249. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41250. return;
  41251. }
  41252. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41253. };
  41254. /**
  41255. * Helps preparing the defines values about the UVs in used in the effect.
  41256. * UVs are shared as much as we can accross chanels in the shaders.
  41257. * @param texture The texture we are preparing the UVs for
  41258. * @param defines The defines to update
  41259. * @param key The chanel key "diffuse", "specular"... used in the shader
  41260. */
  41261. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41262. defines._needUVs = true;
  41263. defines[key] = true;
  41264. if (texture.getTextureMatrix().isIdentity(true)) {
  41265. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41266. if (texture.coordinatesIndex === 0) {
  41267. defines["MAINUV1"] = true;
  41268. }
  41269. else {
  41270. defines["MAINUV2"] = true;
  41271. }
  41272. }
  41273. else {
  41274. defines[key + "DIRECTUV"] = 0;
  41275. }
  41276. };
  41277. /**
  41278. * Binds a texture matrix value to its corrsponding uniform
  41279. * @param texture The texture to bind the matrix for
  41280. * @param uniformBuffer The uniform buffer receivin the data
  41281. * @param key The chanel key "diffuse", "specular"... used in the shader
  41282. */
  41283. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41284. var matrix = texture.getTextureMatrix();
  41285. if (!matrix.isIdentity(true)) {
  41286. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41287. }
  41288. };
  41289. /**
  41290. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41291. * @param mesh defines the current mesh
  41292. * @param scene defines the current scene
  41293. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41294. * @param pointsCloud defines if point cloud rendering has to be turned on
  41295. * @param fogEnabled defines if fog has to be turned on
  41296. * @param alphaTest defines if alpha testing has to be turned on
  41297. * @param defines defines the current list of defines
  41298. */
  41299. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41300. if (defines._areMiscDirty) {
  41301. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41302. defines["POINTSIZE"] = pointsCloud;
  41303. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41304. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41305. defines["ALPHATEST"] = alphaTest;
  41306. }
  41307. };
  41308. /**
  41309. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41310. * @param scene defines the current scene
  41311. * @param engine defines the current engine
  41312. * @param defines specifies the list of active defines
  41313. * @param useInstances defines if instances have to be turned on
  41314. * @param useClipPlane defines if clip plane have to be turned on
  41315. */
  41316. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41317. if (useClipPlane === void 0) { useClipPlane = null; }
  41318. var changed = false;
  41319. if (useClipPlane == null) {
  41320. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41321. }
  41322. if (defines["CLIPPLANE"] !== useClipPlane) {
  41323. defines["CLIPPLANE"] = useClipPlane;
  41324. changed = true;
  41325. }
  41326. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41327. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41328. changed = true;
  41329. }
  41330. if (defines["INSTANCES"] !== useInstances) {
  41331. defines["INSTANCES"] = useInstances;
  41332. changed = true;
  41333. }
  41334. if (changed) {
  41335. defines.markAsUnprocessed();
  41336. }
  41337. };
  41338. /**
  41339. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41340. * @param mesh The mesh containing the geometry data we will draw
  41341. * @param defines The defines to update
  41342. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41343. * @param useBones Precise whether bones should be used or not (override mesh info)
  41344. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41345. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41346. * @returns false if defines are considered not dirty and have not been checked
  41347. */
  41348. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41349. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41350. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41351. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41352. return false;
  41353. }
  41354. defines._normals = defines._needNormals;
  41355. defines._uvs = defines._needUVs;
  41356. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41357. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41358. defines["TANGENT"] = true;
  41359. }
  41360. if (defines._needUVs) {
  41361. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41362. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41363. }
  41364. else {
  41365. defines["UV1"] = false;
  41366. defines["UV2"] = false;
  41367. }
  41368. if (useVertexColor) {
  41369. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41370. defines["VERTEXCOLOR"] = hasVertexColors;
  41371. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41372. }
  41373. if (useBones) {
  41374. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41375. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41376. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41377. }
  41378. else {
  41379. defines["NUM_BONE_INFLUENCERS"] = 0;
  41380. defines["BonesPerMesh"] = 0;
  41381. }
  41382. }
  41383. if (useMorphTargets) {
  41384. var manager = mesh.morphTargetManager;
  41385. if (manager) {
  41386. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41387. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41388. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41389. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41390. }
  41391. else {
  41392. defines["MORPHTARGETS_TANGENT"] = false;
  41393. defines["MORPHTARGETS_NORMAL"] = false;
  41394. defines["MORPHTARGETS"] = false;
  41395. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41396. }
  41397. }
  41398. return true;
  41399. };
  41400. /**
  41401. * Prepares the defines related to the light information passed in parameter
  41402. * @param scene The scene we are intending to draw
  41403. * @param mesh The mesh the effect is compiling for
  41404. * @param defines The defines to update
  41405. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41406. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41407. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41408. * @returns true if normals will be required for the rest of the effect
  41409. */
  41410. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41411. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41412. if (disableLighting === void 0) { disableLighting = false; }
  41413. if (!defines._areLightsDirty) {
  41414. return defines._needNormals;
  41415. }
  41416. var lightIndex = 0;
  41417. var needNormals = false;
  41418. var needRebuild = false;
  41419. var lightmapMode = false;
  41420. var shadowEnabled = false;
  41421. var specularEnabled = false;
  41422. if (scene.lightsEnabled && !disableLighting) {
  41423. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41424. var light = _a[_i];
  41425. needNormals = true;
  41426. if (defines["LIGHT" + lightIndex] === undefined) {
  41427. needRebuild = true;
  41428. }
  41429. defines["LIGHT" + lightIndex] = true;
  41430. defines["SPOTLIGHT" + lightIndex] = false;
  41431. defines["HEMILIGHT" + lightIndex] = false;
  41432. defines["POINTLIGHT" + lightIndex] = false;
  41433. defines["DIRLIGHT" + lightIndex] = false;
  41434. var type;
  41435. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41436. type = "SPOTLIGHT" + lightIndex;
  41437. var spotLight = light;
  41438. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41439. }
  41440. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41441. type = "HEMILIGHT" + lightIndex;
  41442. }
  41443. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41444. type = "POINTLIGHT" + lightIndex;
  41445. }
  41446. else {
  41447. type = "DIRLIGHT" + lightIndex;
  41448. }
  41449. defines[type] = true;
  41450. // Specular
  41451. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41452. specularEnabled = true;
  41453. }
  41454. // Shadows
  41455. defines["SHADOW" + lightIndex] = false;
  41456. defines["SHADOWPCF" + lightIndex] = false;
  41457. defines["SHADOWPCSS" + lightIndex] = false;
  41458. defines["SHADOWPOISSON" + lightIndex] = false;
  41459. defines["SHADOWESM" + lightIndex] = false;
  41460. defines["SHADOWCUBE" + lightIndex] = false;
  41461. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41462. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41463. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41464. var shadowGenerator = light.getShadowGenerator();
  41465. if (shadowGenerator) {
  41466. shadowEnabled = true;
  41467. shadowGenerator.prepareDefines(defines, lightIndex);
  41468. }
  41469. }
  41470. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41471. lightmapMode = true;
  41472. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41473. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41474. }
  41475. else {
  41476. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41477. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41478. }
  41479. lightIndex++;
  41480. if (lightIndex === maxSimultaneousLights)
  41481. break;
  41482. }
  41483. }
  41484. defines["SPECULARTERM"] = specularEnabled;
  41485. defines["SHADOWS"] = shadowEnabled;
  41486. // Resetting all other lights if any
  41487. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41488. if (defines["LIGHT" + index] !== undefined) {
  41489. defines["LIGHT" + index] = false;
  41490. defines["HEMILIGHT" + lightIndex] = false;
  41491. defines["POINTLIGHT" + lightIndex] = false;
  41492. defines["DIRLIGHT" + lightIndex] = false;
  41493. defines["SPOTLIGHT" + lightIndex] = false;
  41494. defines["SHADOW" + lightIndex] = false;
  41495. }
  41496. }
  41497. var caps = scene.getEngine().getCaps();
  41498. if (defines["SHADOWFLOAT"] === undefined) {
  41499. needRebuild = true;
  41500. }
  41501. defines["SHADOWFLOAT"] = shadowEnabled &&
  41502. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41503. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41504. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41505. if (needRebuild) {
  41506. defines.rebuild();
  41507. }
  41508. return needNormals;
  41509. };
  41510. /**
  41511. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41512. * that won t be acctive due to defines being turned off.
  41513. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41514. * @param samplersList The samplers list
  41515. * @param defines The defines helping in the list generation
  41516. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41517. */
  41518. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41519. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41520. var uniformsList;
  41521. var uniformBuffersList = null;
  41522. if (uniformsListOrOptions.uniformsNames) {
  41523. var options = uniformsListOrOptions;
  41524. uniformsList = options.uniformsNames;
  41525. uniformBuffersList = options.uniformBuffersNames;
  41526. samplersList = options.samplers;
  41527. defines = options.defines;
  41528. maxSimultaneousLights = options.maxSimultaneousLights;
  41529. }
  41530. else {
  41531. uniformsList = uniformsListOrOptions;
  41532. if (!samplersList) {
  41533. samplersList = [];
  41534. }
  41535. }
  41536. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41537. if (!defines["LIGHT" + lightIndex]) {
  41538. break;
  41539. }
  41540. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41541. if (uniformBuffersList) {
  41542. uniformBuffersList.push("Light" + lightIndex);
  41543. }
  41544. samplersList.push("shadowSampler" + lightIndex);
  41545. samplersList.push("depthSampler" + lightIndex);
  41546. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41547. samplersList.push("projectionLightSampler" + lightIndex);
  41548. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41549. }
  41550. }
  41551. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41552. uniformsList.push("morphTargetInfluences");
  41553. }
  41554. };
  41555. /**
  41556. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41557. * @param defines The defines to update while falling back
  41558. * @param fallbacks The authorized effect fallbacks
  41559. * @param maxSimultaneousLights The maximum number of lights allowed
  41560. * @param rank the current rank of the Effect
  41561. * @returns The newly affected rank
  41562. */
  41563. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41564. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41565. if (rank === void 0) { rank = 0; }
  41566. var lightFallbackRank = 0;
  41567. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41568. if (!defines["LIGHT" + lightIndex]) {
  41569. break;
  41570. }
  41571. if (lightIndex > 0) {
  41572. lightFallbackRank = rank + lightIndex;
  41573. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41574. }
  41575. if (!defines["SHADOWS"]) {
  41576. if (defines["SHADOW" + lightIndex]) {
  41577. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41578. }
  41579. if (defines["SHADOWPCF" + lightIndex]) {
  41580. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41581. }
  41582. if (defines["SHADOWPCSS" + lightIndex]) {
  41583. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41584. }
  41585. if (defines["SHADOWPOISSON" + lightIndex]) {
  41586. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41587. }
  41588. if (defines["SHADOWESM" + lightIndex]) {
  41589. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41590. }
  41591. }
  41592. }
  41593. return lightFallbackRank++;
  41594. };
  41595. /**
  41596. * Prepares the list of attributes required for morph targets according to the effect defines.
  41597. * @param attribs The current list of supported attribs
  41598. * @param mesh The mesh to prepare the morph targets attributes for
  41599. * @param defines The current Defines of the effect
  41600. */
  41601. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41602. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41603. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41604. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41605. var manager = mesh.morphTargetManager;
  41606. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41607. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41608. for (var index = 0; index < influencers; index++) {
  41609. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41610. if (normal) {
  41611. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41612. }
  41613. if (tangent) {
  41614. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41615. }
  41616. if (attribs.length > maxAttributesCount) {
  41617. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41618. }
  41619. }
  41620. }
  41621. };
  41622. /**
  41623. * Prepares the list of attributes required for bones according to the effect defines.
  41624. * @param attribs The current list of supported attribs
  41625. * @param mesh The mesh to prepare the bones attributes for
  41626. * @param defines The current Defines of the effect
  41627. * @param fallbacks The current efffect fallback strategy
  41628. */
  41629. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41630. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41631. fallbacks.addCPUSkinningFallback(0, mesh);
  41632. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41633. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41634. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41635. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41636. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41637. }
  41638. }
  41639. };
  41640. /**
  41641. * Prepares the list of attributes required for instances according to the effect defines.
  41642. * @param attribs The current list of supported attribs
  41643. * @param defines The current Defines of the effect
  41644. */
  41645. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41646. if (defines["INSTANCES"]) {
  41647. attribs.push("world0");
  41648. attribs.push("world1");
  41649. attribs.push("world2");
  41650. attribs.push("world3");
  41651. }
  41652. };
  41653. /**
  41654. * Binds the light shadow information to the effect for the given mesh.
  41655. * @param light The light containing the generator
  41656. * @param scene The scene the lights belongs to
  41657. * @param mesh The mesh we are binding the information to render
  41658. * @param lightIndex The light index in the effect used to render the mesh
  41659. * @param effect The effect we are binding the data to
  41660. */
  41661. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41662. if (light.shadowEnabled && mesh.receiveShadows) {
  41663. var shadowGenerator = light.getShadowGenerator();
  41664. if (shadowGenerator) {
  41665. shadowGenerator.bindShadowLight(lightIndex, effect);
  41666. }
  41667. }
  41668. };
  41669. /**
  41670. * Binds the light information to the effect.
  41671. * @param light The light containing the generator
  41672. * @param effect The effect we are binding the data to
  41673. * @param lightIndex The light index in the effect used to render
  41674. */
  41675. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41676. light.transferToEffect(effect, lightIndex + "");
  41677. };
  41678. /**
  41679. * Binds the lights information from the scene to the effect for the given mesh.
  41680. * @param scene The scene the lights belongs to
  41681. * @param mesh The mesh we are binding the information to render
  41682. * @param effect The effect we are binding the data to
  41683. * @param defines The generated defines for the effect
  41684. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41685. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41686. */
  41687. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41688. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41689. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41690. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41691. for (var i = 0; i < len; i++) {
  41692. var light = mesh._lightSources[i];
  41693. var iAsString = i.toString();
  41694. var scaledIntensity = light.getScaledIntensity();
  41695. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41696. MaterialHelper.BindLightProperties(light, effect, i);
  41697. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41698. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41699. if (defines["SPECULARTERM"]) {
  41700. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41701. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41702. }
  41703. // Shadows
  41704. if (scene.shadowsEnabled) {
  41705. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41706. }
  41707. light._uniformBuffer.update();
  41708. }
  41709. };
  41710. /**
  41711. * Binds the fog information from the scene to the effect for the given mesh.
  41712. * @param scene The scene the lights belongs to
  41713. * @param mesh The mesh we are binding the information to render
  41714. * @param effect The effect we are binding the data to
  41715. */
  41716. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41717. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41718. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41719. effect.setColor3("vFogColor", scene.fogColor);
  41720. }
  41721. };
  41722. /**
  41723. * Binds the bones information from the mesh to the effect.
  41724. * @param mesh The mesh we are binding the information to render
  41725. * @param effect The effect we are binding the data to
  41726. */
  41727. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41728. if (!effect || !mesh) {
  41729. return;
  41730. }
  41731. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41732. mesh.computeBonesUsingShaders = false;
  41733. }
  41734. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41735. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41736. if (matrices) {
  41737. effect.setMatrices("mBones", matrices);
  41738. }
  41739. }
  41740. };
  41741. /**
  41742. * Binds the morph targets information from the mesh to the effect.
  41743. * @param abstractMesh The mesh we are binding the information to render
  41744. * @param effect The effect we are binding the data to
  41745. */
  41746. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41747. var manager = abstractMesh.morphTargetManager;
  41748. if (!abstractMesh || !manager) {
  41749. return;
  41750. }
  41751. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41752. };
  41753. /**
  41754. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41755. * @param defines The generated defines used in the effect
  41756. * @param effect The effect we are binding the data to
  41757. * @param scene The scene we are willing to render with logarithmic scale for
  41758. */
  41759. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41760. if (defines["LOGARITHMICDEPTH"]) {
  41761. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41762. }
  41763. };
  41764. /**
  41765. * Binds the clip plane information from the scene to the effect.
  41766. * @param scene The scene the clip plane information are extracted from
  41767. * @param effect The effect we are binding the data to
  41768. */
  41769. MaterialHelper.BindClipPlane = function (effect, scene) {
  41770. if (scene.clipPlane) {
  41771. var clipPlane = scene.clipPlane;
  41772. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41773. }
  41774. };
  41775. return MaterialHelper;
  41776. }());
  41777. BABYLON.MaterialHelper = MaterialHelper;
  41778. })(BABYLON || (BABYLON = {}));
  41779. //# sourceMappingURL=babylon.materialHelper.js.map
  41780. var BABYLON;
  41781. (function (BABYLON) {
  41782. var PushMaterial = /** @class */ (function (_super) {
  41783. __extends(PushMaterial, _super);
  41784. function PushMaterial(name, scene) {
  41785. var _this = _super.call(this, name, scene) || this;
  41786. _this._normalMatrix = new BABYLON.Matrix();
  41787. _this.storeEffectOnSubMeshes = true;
  41788. return _this;
  41789. }
  41790. PushMaterial.prototype.getEffect = function () {
  41791. return this._activeEffect;
  41792. };
  41793. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41794. if (!mesh) {
  41795. return false;
  41796. }
  41797. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41798. return true;
  41799. }
  41800. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41801. };
  41802. /**
  41803. * Binds the given world matrix to the active effect
  41804. *
  41805. * @param world the matrix to bind
  41806. */
  41807. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41808. this._activeEffect.setMatrix("world", world);
  41809. };
  41810. /**
  41811. * Binds the given normal matrix to the active effect
  41812. *
  41813. * @param normalMatrix the matrix to bind
  41814. */
  41815. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41816. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41817. };
  41818. PushMaterial.prototype.bind = function (world, mesh) {
  41819. if (!mesh) {
  41820. return;
  41821. }
  41822. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41823. };
  41824. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41825. if (effect === void 0) { effect = null; }
  41826. _super.prototype._afterBind.call(this, mesh);
  41827. this.getScene()._cachedEffect = effect;
  41828. };
  41829. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41830. if (visibility === void 0) { visibility = 1; }
  41831. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41832. };
  41833. return PushMaterial;
  41834. }(BABYLON.Material));
  41835. BABYLON.PushMaterial = PushMaterial;
  41836. })(BABYLON || (BABYLON = {}));
  41837. //# sourceMappingURL=babylon.pushMaterial.js.map
  41838. var BABYLON;
  41839. (function (BABYLON) {
  41840. /** @hidden */
  41841. var StandardMaterialDefines = /** @class */ (function (_super) {
  41842. __extends(StandardMaterialDefines, _super);
  41843. function StandardMaterialDefines() {
  41844. var _this = _super.call(this) || this;
  41845. _this.MAINUV1 = false;
  41846. _this.MAINUV2 = false;
  41847. _this.DIFFUSE = false;
  41848. _this.DIFFUSEDIRECTUV = 0;
  41849. _this.AMBIENT = false;
  41850. _this.AMBIENTDIRECTUV = 0;
  41851. _this.OPACITY = false;
  41852. _this.OPACITYDIRECTUV = 0;
  41853. _this.OPACITYRGB = false;
  41854. _this.REFLECTION = false;
  41855. _this.EMISSIVE = false;
  41856. _this.EMISSIVEDIRECTUV = 0;
  41857. _this.SPECULAR = false;
  41858. _this.SPECULARDIRECTUV = 0;
  41859. _this.BUMP = false;
  41860. _this.BUMPDIRECTUV = 0;
  41861. _this.PARALLAX = false;
  41862. _this.PARALLAXOCCLUSION = false;
  41863. _this.SPECULAROVERALPHA = false;
  41864. _this.CLIPPLANE = false;
  41865. _this.ALPHATEST = false;
  41866. _this.DEPTHPREPASS = false;
  41867. _this.ALPHAFROMDIFFUSE = false;
  41868. _this.POINTSIZE = false;
  41869. _this.FOG = false;
  41870. _this.SPECULARTERM = false;
  41871. _this.DIFFUSEFRESNEL = false;
  41872. _this.OPACITYFRESNEL = false;
  41873. _this.REFLECTIONFRESNEL = false;
  41874. _this.REFRACTIONFRESNEL = false;
  41875. _this.EMISSIVEFRESNEL = false;
  41876. _this.FRESNEL = false;
  41877. _this.NORMAL = false;
  41878. _this.UV1 = false;
  41879. _this.UV2 = false;
  41880. _this.VERTEXCOLOR = false;
  41881. _this.VERTEXALPHA = false;
  41882. _this.NUM_BONE_INFLUENCERS = 0;
  41883. _this.BonesPerMesh = 0;
  41884. _this.INSTANCES = false;
  41885. _this.GLOSSINESS = false;
  41886. _this.ROUGHNESS = false;
  41887. _this.EMISSIVEASILLUMINATION = false;
  41888. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41889. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41890. _this.LIGHTMAP = false;
  41891. _this.LIGHTMAPDIRECTUV = 0;
  41892. _this.OBJECTSPACE_NORMALMAP = false;
  41893. _this.USELIGHTMAPASSHADOWMAP = false;
  41894. _this.REFLECTIONMAP_3D = false;
  41895. _this.REFLECTIONMAP_SPHERICAL = false;
  41896. _this.REFLECTIONMAP_PLANAR = false;
  41897. _this.REFLECTIONMAP_CUBIC = false;
  41898. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41899. _this.REFLECTIONMAP_PROJECTION = false;
  41900. _this.REFLECTIONMAP_SKYBOX = false;
  41901. _this.REFLECTIONMAP_EXPLICIT = false;
  41902. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41903. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41904. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41905. _this.INVERTCUBICMAP = false;
  41906. _this.LOGARITHMICDEPTH = false;
  41907. _this.REFRACTION = false;
  41908. _this.REFRACTIONMAP_3D = false;
  41909. _this.REFLECTIONOVERALPHA = false;
  41910. _this.TWOSIDEDLIGHTING = false;
  41911. _this.SHADOWFLOAT = false;
  41912. _this.MORPHTARGETS = false;
  41913. _this.MORPHTARGETS_NORMAL = false;
  41914. _this.MORPHTARGETS_TANGENT = false;
  41915. _this.NUM_MORPH_INFLUENCERS = 0;
  41916. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41917. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41918. _this.IMAGEPROCESSING = false;
  41919. _this.VIGNETTE = false;
  41920. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41921. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41922. _this.TONEMAPPING = false;
  41923. _this.CONTRAST = false;
  41924. _this.COLORCURVES = false;
  41925. _this.COLORGRADING = false;
  41926. _this.COLORGRADING3D = false;
  41927. _this.SAMPLER3DGREENDEPTH = false;
  41928. _this.SAMPLER3DBGRMAP = false;
  41929. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41930. /**
  41931. * If the reflection texture on this material is in linear color space
  41932. * @hidden
  41933. */
  41934. _this.IS_REFLECTION_LINEAR = false;
  41935. /**
  41936. * If the refraction texture on this material is in linear color space
  41937. * @hidden
  41938. */
  41939. _this.IS_REFRACTION_LINEAR = false;
  41940. _this.EXPOSURE = false;
  41941. _this.rebuild();
  41942. return _this;
  41943. }
  41944. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41945. var modes = [
  41946. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41947. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41948. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41949. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41950. ];
  41951. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41952. var mode = modes_1[_i];
  41953. this[mode] = (mode === modeToEnable);
  41954. }
  41955. };
  41956. return StandardMaterialDefines;
  41957. }(BABYLON.MaterialDefines));
  41958. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41959. var StandardMaterial = /** @class */ (function (_super) {
  41960. __extends(StandardMaterial, _super);
  41961. function StandardMaterial(name, scene) {
  41962. var _this = _super.call(this, name, scene) || this;
  41963. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41964. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41965. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41966. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41967. _this.specularPower = 64;
  41968. _this._useAlphaFromDiffuseTexture = false;
  41969. _this._useEmissiveAsIllumination = false;
  41970. _this._linkEmissiveWithDiffuse = false;
  41971. _this._useSpecularOverAlpha = false;
  41972. _this._useReflectionOverAlpha = false;
  41973. _this._disableLighting = false;
  41974. _this._useObjectSpaceNormalMap = false;
  41975. _this._useParallax = false;
  41976. _this._useParallaxOcclusion = false;
  41977. _this.parallaxScaleBias = 0.05;
  41978. _this._roughness = 0;
  41979. _this.indexOfRefraction = 0.98;
  41980. _this.invertRefractionY = true;
  41981. /**
  41982. * Defines the alpha limits in alpha test mode
  41983. */
  41984. _this.alphaCutOff = 0.4;
  41985. _this._useLightmapAsShadowmap = false;
  41986. _this._useReflectionFresnelFromSpecular = false;
  41987. _this._useGlossinessFromSpecularMapAlpha = false;
  41988. _this._maxSimultaneousLights = 4;
  41989. /**
  41990. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41991. */
  41992. _this._invertNormalMapX = false;
  41993. /**
  41994. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41995. */
  41996. _this._invertNormalMapY = false;
  41997. /**
  41998. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41999. */
  42000. _this._twoSidedLighting = false;
  42001. _this._renderTargets = new BABYLON.SmartArray(16);
  42002. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42003. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42004. // Setup the default processing configuration to the scene.
  42005. _this._attachImageProcessingConfiguration(null);
  42006. _this.getRenderTargetTextures = function () {
  42007. _this._renderTargets.reset();
  42008. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42009. _this._renderTargets.push(_this._reflectionTexture);
  42010. }
  42011. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42012. _this._renderTargets.push(_this._refractionTexture);
  42013. }
  42014. return _this._renderTargets;
  42015. };
  42016. return _this;
  42017. }
  42018. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42019. /**
  42020. * Gets the image processing configuration used either in this material.
  42021. */
  42022. get: function () {
  42023. return this._imageProcessingConfiguration;
  42024. },
  42025. /**
  42026. * Sets the Default image processing configuration used either in the this material.
  42027. *
  42028. * If sets to null, the scene one is in use.
  42029. */
  42030. set: function (value) {
  42031. this._attachImageProcessingConfiguration(value);
  42032. // Ensure the effect will be rebuilt.
  42033. this._markAllSubMeshesAsTexturesDirty();
  42034. },
  42035. enumerable: true,
  42036. configurable: true
  42037. });
  42038. /**
  42039. * Attaches a new image processing configuration to the Standard Material.
  42040. * @param configuration
  42041. */
  42042. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42043. var _this = this;
  42044. if (configuration === this._imageProcessingConfiguration) {
  42045. return;
  42046. }
  42047. // Detaches observer.
  42048. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42049. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42050. }
  42051. // Pick the scene configuration if needed.
  42052. if (!configuration) {
  42053. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42054. }
  42055. else {
  42056. this._imageProcessingConfiguration = configuration;
  42057. }
  42058. // Attaches observer.
  42059. if (this._imageProcessingConfiguration) {
  42060. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42061. _this._markAllSubMeshesAsImageProcessingDirty();
  42062. });
  42063. }
  42064. };
  42065. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42066. /**
  42067. * Gets wether the color curves effect is enabled.
  42068. */
  42069. get: function () {
  42070. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42071. },
  42072. /**
  42073. * Sets wether the color curves effect is enabled.
  42074. */
  42075. set: function (value) {
  42076. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42077. },
  42078. enumerable: true,
  42079. configurable: true
  42080. });
  42081. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42082. /**
  42083. * Gets wether the color grading effect is enabled.
  42084. */
  42085. get: function () {
  42086. return this.imageProcessingConfiguration.colorGradingEnabled;
  42087. },
  42088. /**
  42089. * Gets wether the color grading effect is enabled.
  42090. */
  42091. set: function (value) {
  42092. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42093. },
  42094. enumerable: true,
  42095. configurable: true
  42096. });
  42097. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42098. /**
  42099. * Gets wether tonemapping is enabled or not.
  42100. */
  42101. get: function () {
  42102. return this._imageProcessingConfiguration.toneMappingEnabled;
  42103. },
  42104. /**
  42105. * Sets wether tonemapping is enabled or not
  42106. */
  42107. set: function (value) {
  42108. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42109. },
  42110. enumerable: true,
  42111. configurable: true
  42112. });
  42113. ;
  42114. ;
  42115. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42116. /**
  42117. * The camera exposure used on this material.
  42118. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42119. * This corresponds to a photographic exposure.
  42120. */
  42121. get: function () {
  42122. return this._imageProcessingConfiguration.exposure;
  42123. },
  42124. /**
  42125. * The camera exposure used on this material.
  42126. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42127. * This corresponds to a photographic exposure.
  42128. */
  42129. set: function (value) {
  42130. this._imageProcessingConfiguration.exposure = value;
  42131. },
  42132. enumerable: true,
  42133. configurable: true
  42134. });
  42135. ;
  42136. ;
  42137. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42138. /**
  42139. * Gets The camera contrast used on this material.
  42140. */
  42141. get: function () {
  42142. return this._imageProcessingConfiguration.contrast;
  42143. },
  42144. /**
  42145. * Sets The camera contrast used on this material.
  42146. */
  42147. set: function (value) {
  42148. this._imageProcessingConfiguration.contrast = value;
  42149. },
  42150. enumerable: true,
  42151. configurable: true
  42152. });
  42153. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42154. /**
  42155. * Gets the Color Grading 2D Lookup Texture.
  42156. */
  42157. get: function () {
  42158. return this._imageProcessingConfiguration.colorGradingTexture;
  42159. },
  42160. /**
  42161. * Sets the Color Grading 2D Lookup Texture.
  42162. */
  42163. set: function (value) {
  42164. this._imageProcessingConfiguration.colorGradingTexture = value;
  42165. },
  42166. enumerable: true,
  42167. configurable: true
  42168. });
  42169. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42170. /**
  42171. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42172. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42173. * 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;
  42174. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42175. */
  42176. get: function () {
  42177. return this._imageProcessingConfiguration.colorCurves;
  42178. },
  42179. /**
  42180. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42181. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42182. * 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;
  42183. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42184. */
  42185. set: function (value) {
  42186. this._imageProcessingConfiguration.colorCurves = value;
  42187. },
  42188. enumerable: true,
  42189. configurable: true
  42190. });
  42191. StandardMaterial.prototype.getClassName = function () {
  42192. return "StandardMaterial";
  42193. };
  42194. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42195. get: function () {
  42196. return this._useLogarithmicDepth;
  42197. },
  42198. set: function (value) {
  42199. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42200. this._markAllSubMeshesAsMiscDirty();
  42201. },
  42202. enumerable: true,
  42203. configurable: true
  42204. });
  42205. StandardMaterial.prototype.needAlphaBlending = function () {
  42206. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42207. };
  42208. StandardMaterial.prototype.needAlphaTesting = function () {
  42209. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42210. };
  42211. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42212. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42213. };
  42214. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42215. return this._diffuseTexture;
  42216. };
  42217. /**
  42218. * Child classes can use it to update shaders
  42219. */
  42220. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42221. if (useInstances === void 0) { useInstances = false; }
  42222. if (subMesh.effect && this.isFrozen) {
  42223. if (this._wasPreviouslyReady && subMesh.effect) {
  42224. return true;
  42225. }
  42226. }
  42227. if (!subMesh._materialDefines) {
  42228. subMesh._materialDefines = new StandardMaterialDefines();
  42229. }
  42230. var scene = this.getScene();
  42231. var defines = subMesh._materialDefines;
  42232. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42233. if (defines._renderId === scene.getRenderId()) {
  42234. return true;
  42235. }
  42236. }
  42237. var engine = scene.getEngine();
  42238. // Lights
  42239. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42240. // Textures
  42241. if (defines._areTexturesDirty) {
  42242. defines._needUVs = false;
  42243. defines.MAINUV1 = false;
  42244. defines.MAINUV2 = false;
  42245. if (scene.texturesEnabled) {
  42246. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42247. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42248. return false;
  42249. }
  42250. else {
  42251. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42252. }
  42253. }
  42254. else {
  42255. defines.DIFFUSE = false;
  42256. }
  42257. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42258. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42259. return false;
  42260. }
  42261. else {
  42262. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42263. }
  42264. }
  42265. else {
  42266. defines.AMBIENT = false;
  42267. }
  42268. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42269. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42270. return false;
  42271. }
  42272. else {
  42273. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42274. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42275. }
  42276. }
  42277. else {
  42278. defines.OPACITY = false;
  42279. }
  42280. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42281. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42282. return false;
  42283. }
  42284. else {
  42285. defines._needNormals = true;
  42286. defines.REFLECTION = true;
  42287. defines.ROUGHNESS = (this._roughness > 0);
  42288. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42289. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42290. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42291. switch (this._reflectionTexture.coordinatesMode) {
  42292. case BABYLON.Texture.EXPLICIT_MODE:
  42293. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42294. break;
  42295. case BABYLON.Texture.PLANAR_MODE:
  42296. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42297. break;
  42298. case BABYLON.Texture.PROJECTION_MODE:
  42299. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42300. break;
  42301. case BABYLON.Texture.SKYBOX_MODE:
  42302. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42303. break;
  42304. case BABYLON.Texture.SPHERICAL_MODE:
  42305. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42306. break;
  42307. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42308. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42309. break;
  42310. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42311. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42312. break;
  42313. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42314. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42315. break;
  42316. case BABYLON.Texture.CUBIC_MODE:
  42317. case BABYLON.Texture.INVCUBIC_MODE:
  42318. default:
  42319. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42320. break;
  42321. }
  42322. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42323. }
  42324. }
  42325. else {
  42326. defines.REFLECTION = false;
  42327. }
  42328. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42329. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42330. return false;
  42331. }
  42332. else {
  42333. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42334. }
  42335. }
  42336. else {
  42337. defines.EMISSIVE = false;
  42338. }
  42339. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42340. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42341. return false;
  42342. }
  42343. else {
  42344. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42345. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42346. }
  42347. }
  42348. else {
  42349. defines.LIGHTMAP = false;
  42350. }
  42351. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42352. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42353. return false;
  42354. }
  42355. else {
  42356. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42357. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42358. }
  42359. }
  42360. else {
  42361. defines.SPECULAR = false;
  42362. }
  42363. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42364. // Bump texure can not be not blocking.
  42365. if (!this._bumpTexture.isReady()) {
  42366. return false;
  42367. }
  42368. else {
  42369. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42370. defines.PARALLAX = this._useParallax;
  42371. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42372. }
  42373. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42374. }
  42375. else {
  42376. defines.BUMP = false;
  42377. }
  42378. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42379. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42380. return false;
  42381. }
  42382. else {
  42383. defines._needUVs = true;
  42384. defines.REFRACTION = true;
  42385. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42386. }
  42387. }
  42388. else {
  42389. defines.REFRACTION = false;
  42390. }
  42391. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42392. }
  42393. else {
  42394. defines.DIFFUSE = false;
  42395. defines.AMBIENT = false;
  42396. defines.OPACITY = false;
  42397. defines.REFLECTION = false;
  42398. defines.EMISSIVE = false;
  42399. defines.LIGHTMAP = false;
  42400. defines.BUMP = false;
  42401. defines.REFRACTION = false;
  42402. }
  42403. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42404. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42405. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42406. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42407. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42408. }
  42409. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42410. if (!this._imageProcessingConfiguration.isReady()) {
  42411. return false;
  42412. }
  42413. this._imageProcessingConfiguration.prepareDefines(defines);
  42414. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42415. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42416. }
  42417. if (defines._areFresnelDirty) {
  42418. if (StandardMaterial.FresnelEnabled) {
  42419. // Fresnel
  42420. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42421. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42422. this._reflectionFresnelParameters) {
  42423. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42424. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42425. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42426. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42427. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42428. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42429. defines._needNormals = true;
  42430. defines.FRESNEL = true;
  42431. }
  42432. }
  42433. else {
  42434. defines.FRESNEL = false;
  42435. }
  42436. }
  42437. // Misc.
  42438. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42439. // Attribs
  42440. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42441. // Values that need to be evaluated on every frame
  42442. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42443. // Get correct effect
  42444. if (defines.isDirty) {
  42445. defines.markAsProcessed();
  42446. scene.resetCachedMaterial();
  42447. // Fallbacks
  42448. var fallbacks = new BABYLON.EffectFallbacks();
  42449. if (defines.REFLECTION) {
  42450. fallbacks.addFallback(0, "REFLECTION");
  42451. }
  42452. if (defines.SPECULAR) {
  42453. fallbacks.addFallback(0, "SPECULAR");
  42454. }
  42455. if (defines.BUMP) {
  42456. fallbacks.addFallback(0, "BUMP");
  42457. }
  42458. if (defines.PARALLAX) {
  42459. fallbacks.addFallback(1, "PARALLAX");
  42460. }
  42461. if (defines.PARALLAXOCCLUSION) {
  42462. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42463. }
  42464. if (defines.SPECULAROVERALPHA) {
  42465. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42466. }
  42467. if (defines.FOG) {
  42468. fallbacks.addFallback(1, "FOG");
  42469. }
  42470. if (defines.POINTSIZE) {
  42471. fallbacks.addFallback(0, "POINTSIZE");
  42472. }
  42473. if (defines.LOGARITHMICDEPTH) {
  42474. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42475. }
  42476. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42477. if (defines.SPECULARTERM) {
  42478. fallbacks.addFallback(0, "SPECULARTERM");
  42479. }
  42480. if (defines.DIFFUSEFRESNEL) {
  42481. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42482. }
  42483. if (defines.OPACITYFRESNEL) {
  42484. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42485. }
  42486. if (defines.REFLECTIONFRESNEL) {
  42487. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42488. }
  42489. if (defines.EMISSIVEFRESNEL) {
  42490. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42491. }
  42492. if (defines.FRESNEL) {
  42493. fallbacks.addFallback(4, "FRESNEL");
  42494. }
  42495. //Attributes
  42496. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42497. if (defines.NORMAL) {
  42498. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42499. }
  42500. if (defines.UV1) {
  42501. attribs.push(BABYLON.VertexBuffer.UVKind);
  42502. }
  42503. if (defines.UV2) {
  42504. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42505. }
  42506. if (defines.VERTEXCOLOR) {
  42507. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42508. }
  42509. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42510. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42511. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42512. var shaderName = "default";
  42513. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42514. "vFogInfos", "vFogColor", "pointSize",
  42515. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42516. "mBones",
  42517. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42518. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42519. "vReflectionPosition", "vReflectionSize",
  42520. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42521. ];
  42522. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42523. var uniformBuffers = ["Material", "Scene"];
  42524. if (BABYLON.ImageProcessingConfiguration) {
  42525. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42526. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42527. }
  42528. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42529. uniformsNames: uniforms,
  42530. uniformBuffersNames: uniformBuffers,
  42531. samplers: samplers,
  42532. defines: defines,
  42533. maxSimultaneousLights: this._maxSimultaneousLights
  42534. });
  42535. if (this.customShaderNameResolve) {
  42536. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42537. }
  42538. var join = defines.toString();
  42539. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42540. attributes: attribs,
  42541. uniformsNames: uniforms,
  42542. uniformBuffersNames: uniformBuffers,
  42543. samplers: samplers,
  42544. defines: join,
  42545. fallbacks: fallbacks,
  42546. onCompiled: this.onCompiled,
  42547. onError: this.onError,
  42548. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42549. }, engine), defines);
  42550. this.buildUniformLayout();
  42551. }
  42552. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42553. return false;
  42554. }
  42555. defines._renderId = scene.getRenderId();
  42556. this._wasPreviouslyReady = true;
  42557. return true;
  42558. };
  42559. StandardMaterial.prototype.buildUniformLayout = function () {
  42560. // Order is important !
  42561. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42562. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42563. this._uniformBuffer.addUniform("opacityParts", 4);
  42564. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42565. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42566. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42567. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42568. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42569. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42570. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42571. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42572. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42573. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42574. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42575. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42576. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42577. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42578. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42579. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42580. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42581. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42582. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42583. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42584. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42585. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42586. this._uniformBuffer.addUniform("specularMatrix", 16);
  42587. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42588. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42589. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42590. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42591. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42592. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42593. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42594. this._uniformBuffer.addUniform("pointSize", 1);
  42595. this._uniformBuffer.create();
  42596. };
  42597. StandardMaterial.prototype.unbind = function () {
  42598. if (this._activeEffect) {
  42599. var needFlag = false;
  42600. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42601. this._activeEffect.setTexture("reflection2DSampler", null);
  42602. needFlag = true;
  42603. }
  42604. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42605. this._activeEffect.setTexture("refraction2DSampler", null);
  42606. needFlag = true;
  42607. }
  42608. if (needFlag) {
  42609. this._markAllSubMeshesAsTexturesDirty();
  42610. }
  42611. }
  42612. _super.prototype.unbind.call(this);
  42613. };
  42614. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42615. var scene = this.getScene();
  42616. var defines = subMesh._materialDefines;
  42617. if (!defines) {
  42618. return;
  42619. }
  42620. var effect = subMesh.effect;
  42621. if (!effect) {
  42622. return;
  42623. }
  42624. this._activeEffect = effect;
  42625. // Matrices
  42626. this.bindOnlyWorldMatrix(world);
  42627. // Normal Matrix
  42628. if (defines.OBJECTSPACE_NORMALMAP) {
  42629. world.toNormalMatrix(this._normalMatrix);
  42630. this.bindOnlyNormalMatrix(this._normalMatrix);
  42631. }
  42632. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42633. // Bones
  42634. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42635. if (mustRebind) {
  42636. this._uniformBuffer.bindToEffect(effect, "Material");
  42637. this.bindViewProjection(effect);
  42638. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42639. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42640. // Fresnel
  42641. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42642. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42643. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42644. }
  42645. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42646. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42647. }
  42648. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42649. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42650. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42651. }
  42652. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42653. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42654. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42655. }
  42656. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42657. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42658. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42659. }
  42660. }
  42661. // Textures
  42662. if (scene.texturesEnabled) {
  42663. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42664. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42665. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42666. if (this._diffuseTexture.hasAlpha) {
  42667. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42668. }
  42669. }
  42670. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42671. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42672. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42673. }
  42674. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42675. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42676. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42677. }
  42678. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42679. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42680. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42681. if (this._reflectionTexture.boundingBoxSize) {
  42682. var cubeTexture = this._reflectionTexture;
  42683. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42684. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42685. }
  42686. }
  42687. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42688. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42689. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42690. }
  42691. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42692. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42693. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42694. }
  42695. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42696. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42697. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42698. }
  42699. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42700. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42701. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42702. if (scene._mirroredCameraPosition) {
  42703. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42704. }
  42705. else {
  42706. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42707. }
  42708. }
  42709. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42710. var depth = 1.0;
  42711. if (!this._refractionTexture.isCube) {
  42712. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42713. if (this._refractionTexture.depth) {
  42714. depth = this._refractionTexture.depth;
  42715. }
  42716. }
  42717. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42718. }
  42719. }
  42720. // Point size
  42721. if (this.pointsCloud) {
  42722. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42723. }
  42724. if (defines.SPECULARTERM) {
  42725. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42726. }
  42727. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42728. // Diffuse
  42729. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42730. }
  42731. // Textures
  42732. if (scene.texturesEnabled) {
  42733. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42734. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42735. }
  42736. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42737. effect.setTexture("ambientSampler", this._ambientTexture);
  42738. }
  42739. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42740. effect.setTexture("opacitySampler", this._opacityTexture);
  42741. }
  42742. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42743. if (this._reflectionTexture.isCube) {
  42744. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42745. }
  42746. else {
  42747. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42748. }
  42749. }
  42750. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42751. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42752. }
  42753. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42754. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42755. }
  42756. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42757. effect.setTexture("specularSampler", this._specularTexture);
  42758. }
  42759. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42760. effect.setTexture("bumpSampler", this._bumpTexture);
  42761. }
  42762. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42763. var depth = 1.0;
  42764. if (this._refractionTexture.isCube) {
  42765. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42766. }
  42767. else {
  42768. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42769. }
  42770. }
  42771. }
  42772. // Clip plane
  42773. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42774. // Colors
  42775. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42776. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42777. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42778. }
  42779. if (mustRebind || !this.isFrozen) {
  42780. // Lights
  42781. if (scene.lightsEnabled && !this._disableLighting) {
  42782. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42783. }
  42784. // View
  42785. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42786. this.bindView(effect);
  42787. }
  42788. // Fog
  42789. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42790. // Morph targets
  42791. if (defines.NUM_MORPH_INFLUENCERS) {
  42792. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42793. }
  42794. // Log. depth
  42795. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42796. // image processing
  42797. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42798. this._imageProcessingConfiguration.bind(this._activeEffect);
  42799. }
  42800. }
  42801. this._uniformBuffer.update();
  42802. this._afterBind(mesh, this._activeEffect);
  42803. };
  42804. StandardMaterial.prototype.getAnimatables = function () {
  42805. var results = [];
  42806. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42807. results.push(this._diffuseTexture);
  42808. }
  42809. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42810. results.push(this._ambientTexture);
  42811. }
  42812. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42813. results.push(this._opacityTexture);
  42814. }
  42815. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42816. results.push(this._reflectionTexture);
  42817. }
  42818. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42819. results.push(this._emissiveTexture);
  42820. }
  42821. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42822. results.push(this._specularTexture);
  42823. }
  42824. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42825. results.push(this._bumpTexture);
  42826. }
  42827. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42828. results.push(this._lightmapTexture);
  42829. }
  42830. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42831. results.push(this._refractionTexture);
  42832. }
  42833. return results;
  42834. };
  42835. StandardMaterial.prototype.getActiveTextures = function () {
  42836. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42837. if (this._diffuseTexture) {
  42838. activeTextures.push(this._diffuseTexture);
  42839. }
  42840. if (this._ambientTexture) {
  42841. activeTextures.push(this._ambientTexture);
  42842. }
  42843. if (this._opacityTexture) {
  42844. activeTextures.push(this._opacityTexture);
  42845. }
  42846. if (this._reflectionTexture) {
  42847. activeTextures.push(this._reflectionTexture);
  42848. }
  42849. if (this._emissiveTexture) {
  42850. activeTextures.push(this._emissiveTexture);
  42851. }
  42852. if (this._specularTexture) {
  42853. activeTextures.push(this._specularTexture);
  42854. }
  42855. if (this._bumpTexture) {
  42856. activeTextures.push(this._bumpTexture);
  42857. }
  42858. if (this._lightmapTexture) {
  42859. activeTextures.push(this._lightmapTexture);
  42860. }
  42861. if (this._refractionTexture) {
  42862. activeTextures.push(this._refractionTexture);
  42863. }
  42864. return activeTextures;
  42865. };
  42866. StandardMaterial.prototype.hasTexture = function (texture) {
  42867. if (_super.prototype.hasTexture.call(this, texture)) {
  42868. return true;
  42869. }
  42870. if (this._diffuseTexture === texture) {
  42871. return true;
  42872. }
  42873. if (this._ambientTexture === texture) {
  42874. return true;
  42875. }
  42876. if (this._opacityTexture === texture) {
  42877. return true;
  42878. }
  42879. if (this._reflectionTexture === texture) {
  42880. return true;
  42881. }
  42882. if (this._emissiveTexture === texture) {
  42883. return true;
  42884. }
  42885. if (this._specularTexture === texture) {
  42886. return true;
  42887. }
  42888. if (this._bumpTexture === texture) {
  42889. return true;
  42890. }
  42891. if (this._lightmapTexture === texture) {
  42892. return true;
  42893. }
  42894. if (this._refractionTexture === texture) {
  42895. return true;
  42896. }
  42897. return false;
  42898. };
  42899. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42900. if (forceDisposeTextures) {
  42901. if (this._diffuseTexture) {
  42902. this._diffuseTexture.dispose();
  42903. }
  42904. if (this._ambientTexture) {
  42905. this._ambientTexture.dispose();
  42906. }
  42907. if (this._opacityTexture) {
  42908. this._opacityTexture.dispose();
  42909. }
  42910. if (this._reflectionTexture) {
  42911. this._reflectionTexture.dispose();
  42912. }
  42913. if (this._emissiveTexture) {
  42914. this._emissiveTexture.dispose();
  42915. }
  42916. if (this._specularTexture) {
  42917. this._specularTexture.dispose();
  42918. }
  42919. if (this._bumpTexture) {
  42920. this._bumpTexture.dispose();
  42921. }
  42922. if (this._lightmapTexture) {
  42923. this._lightmapTexture.dispose();
  42924. }
  42925. if (this._refractionTexture) {
  42926. this._refractionTexture.dispose();
  42927. }
  42928. }
  42929. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42930. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42931. }
  42932. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42933. };
  42934. StandardMaterial.prototype.clone = function (name) {
  42935. var _this = this;
  42936. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42937. result.name = name;
  42938. result.id = name;
  42939. return result;
  42940. };
  42941. StandardMaterial.prototype.serialize = function () {
  42942. return BABYLON.SerializationHelper.Serialize(this);
  42943. };
  42944. // Statics
  42945. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42946. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42947. };
  42948. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42949. get: function () {
  42950. return StandardMaterial._DiffuseTextureEnabled;
  42951. },
  42952. set: function (value) {
  42953. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42954. return;
  42955. }
  42956. StandardMaterial._DiffuseTextureEnabled = value;
  42957. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42958. },
  42959. enumerable: true,
  42960. configurable: true
  42961. });
  42962. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42963. get: function () {
  42964. return StandardMaterial._AmbientTextureEnabled;
  42965. },
  42966. set: function (value) {
  42967. if (StandardMaterial._AmbientTextureEnabled === value) {
  42968. return;
  42969. }
  42970. StandardMaterial._AmbientTextureEnabled = value;
  42971. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42972. },
  42973. enumerable: true,
  42974. configurable: true
  42975. });
  42976. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42977. get: function () {
  42978. return StandardMaterial._OpacityTextureEnabled;
  42979. },
  42980. set: function (value) {
  42981. if (StandardMaterial._OpacityTextureEnabled === value) {
  42982. return;
  42983. }
  42984. StandardMaterial._OpacityTextureEnabled = value;
  42985. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42986. },
  42987. enumerable: true,
  42988. configurable: true
  42989. });
  42990. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42991. get: function () {
  42992. return StandardMaterial._ReflectionTextureEnabled;
  42993. },
  42994. set: function (value) {
  42995. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42996. return;
  42997. }
  42998. StandardMaterial._ReflectionTextureEnabled = value;
  42999. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43000. },
  43001. enumerable: true,
  43002. configurable: true
  43003. });
  43004. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43005. get: function () {
  43006. return StandardMaterial._EmissiveTextureEnabled;
  43007. },
  43008. set: function (value) {
  43009. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43010. return;
  43011. }
  43012. StandardMaterial._EmissiveTextureEnabled = value;
  43013. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43014. },
  43015. enumerable: true,
  43016. configurable: true
  43017. });
  43018. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43019. get: function () {
  43020. return StandardMaterial._SpecularTextureEnabled;
  43021. },
  43022. set: function (value) {
  43023. if (StandardMaterial._SpecularTextureEnabled === value) {
  43024. return;
  43025. }
  43026. StandardMaterial._SpecularTextureEnabled = value;
  43027. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43028. },
  43029. enumerable: true,
  43030. configurable: true
  43031. });
  43032. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43033. get: function () {
  43034. return StandardMaterial._BumpTextureEnabled;
  43035. },
  43036. set: function (value) {
  43037. if (StandardMaterial._BumpTextureEnabled === value) {
  43038. return;
  43039. }
  43040. StandardMaterial._BumpTextureEnabled = value;
  43041. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43042. },
  43043. enumerable: true,
  43044. configurable: true
  43045. });
  43046. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43047. get: function () {
  43048. return StandardMaterial._LightmapTextureEnabled;
  43049. },
  43050. set: function (value) {
  43051. if (StandardMaterial._LightmapTextureEnabled === value) {
  43052. return;
  43053. }
  43054. StandardMaterial._LightmapTextureEnabled = value;
  43055. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43056. },
  43057. enumerable: true,
  43058. configurable: true
  43059. });
  43060. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43061. get: function () {
  43062. return StandardMaterial._RefractionTextureEnabled;
  43063. },
  43064. set: function (value) {
  43065. if (StandardMaterial._RefractionTextureEnabled === value) {
  43066. return;
  43067. }
  43068. StandardMaterial._RefractionTextureEnabled = value;
  43069. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43070. },
  43071. enumerable: true,
  43072. configurable: true
  43073. });
  43074. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43075. get: function () {
  43076. return StandardMaterial._ColorGradingTextureEnabled;
  43077. },
  43078. set: function (value) {
  43079. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43080. return;
  43081. }
  43082. StandardMaterial._ColorGradingTextureEnabled = value;
  43083. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43084. },
  43085. enumerable: true,
  43086. configurable: true
  43087. });
  43088. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43089. get: function () {
  43090. return StandardMaterial._FresnelEnabled;
  43091. },
  43092. set: function (value) {
  43093. if (StandardMaterial._FresnelEnabled === value) {
  43094. return;
  43095. }
  43096. StandardMaterial._FresnelEnabled = value;
  43097. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43098. },
  43099. enumerable: true,
  43100. configurable: true
  43101. });
  43102. // Flags used to enable or disable a type of texture for all Standard Materials
  43103. StandardMaterial._DiffuseTextureEnabled = true;
  43104. StandardMaterial._AmbientTextureEnabled = true;
  43105. StandardMaterial._OpacityTextureEnabled = true;
  43106. StandardMaterial._ReflectionTextureEnabled = true;
  43107. StandardMaterial._EmissiveTextureEnabled = true;
  43108. StandardMaterial._SpecularTextureEnabled = true;
  43109. StandardMaterial._BumpTextureEnabled = true;
  43110. StandardMaterial._LightmapTextureEnabled = true;
  43111. StandardMaterial._RefractionTextureEnabled = true;
  43112. StandardMaterial._ColorGradingTextureEnabled = true;
  43113. StandardMaterial._FresnelEnabled = true;
  43114. __decorate([
  43115. BABYLON.serializeAsTexture("diffuseTexture")
  43116. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43117. __decorate([
  43118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43119. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43120. __decorate([
  43121. BABYLON.serializeAsTexture("ambientTexture")
  43122. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43123. __decorate([
  43124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43125. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43126. __decorate([
  43127. BABYLON.serializeAsTexture("opacityTexture")
  43128. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43129. __decorate([
  43130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43131. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43132. __decorate([
  43133. BABYLON.serializeAsTexture("reflectionTexture")
  43134. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43135. __decorate([
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43137. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43138. __decorate([
  43139. BABYLON.serializeAsTexture("emissiveTexture")
  43140. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43141. __decorate([
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43143. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43144. __decorate([
  43145. BABYLON.serializeAsTexture("specularTexture")
  43146. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43147. __decorate([
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43149. ], StandardMaterial.prototype, "specularTexture", void 0);
  43150. __decorate([
  43151. BABYLON.serializeAsTexture("bumpTexture")
  43152. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43153. __decorate([
  43154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43155. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43156. __decorate([
  43157. BABYLON.serializeAsTexture("lightmapTexture")
  43158. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43159. __decorate([
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43161. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43162. __decorate([
  43163. BABYLON.serializeAsTexture("refractionTexture")
  43164. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43165. __decorate([
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43167. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43168. __decorate([
  43169. BABYLON.serializeAsColor3("ambient")
  43170. ], StandardMaterial.prototype, "ambientColor", void 0);
  43171. __decorate([
  43172. BABYLON.serializeAsColor3("diffuse")
  43173. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43174. __decorate([
  43175. BABYLON.serializeAsColor3("specular")
  43176. ], StandardMaterial.prototype, "specularColor", void 0);
  43177. __decorate([
  43178. BABYLON.serializeAsColor3("emissive")
  43179. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43180. __decorate([
  43181. BABYLON.serialize()
  43182. ], StandardMaterial.prototype, "specularPower", void 0);
  43183. __decorate([
  43184. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43185. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43186. __decorate([
  43187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43188. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43189. __decorate([
  43190. BABYLON.serialize("useEmissiveAsIllumination")
  43191. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43192. __decorate([
  43193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43194. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43195. __decorate([
  43196. BABYLON.serialize("linkEmissiveWithDiffuse")
  43197. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43198. __decorate([
  43199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43200. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43201. __decorate([
  43202. BABYLON.serialize("useSpecularOverAlpha")
  43203. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43204. __decorate([
  43205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43206. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43207. __decorate([
  43208. BABYLON.serialize("useReflectionOverAlpha")
  43209. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43210. __decorate([
  43211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43212. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43213. __decorate([
  43214. BABYLON.serialize("disableLighting")
  43215. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43216. __decorate([
  43217. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43218. ], StandardMaterial.prototype, "disableLighting", void 0);
  43219. __decorate([
  43220. BABYLON.serialize("useObjectSpaceNormalMap")
  43221. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43222. __decorate([
  43223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43224. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43225. __decorate([
  43226. BABYLON.serialize("useParallax")
  43227. ], StandardMaterial.prototype, "_useParallax", void 0);
  43228. __decorate([
  43229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43230. ], StandardMaterial.prototype, "useParallax", void 0);
  43231. __decorate([
  43232. BABYLON.serialize("useParallaxOcclusion")
  43233. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43234. __decorate([
  43235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43236. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43237. __decorate([
  43238. BABYLON.serialize()
  43239. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43240. __decorate([
  43241. BABYLON.serialize("roughness")
  43242. ], StandardMaterial.prototype, "_roughness", void 0);
  43243. __decorate([
  43244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43245. ], StandardMaterial.prototype, "roughness", void 0);
  43246. __decorate([
  43247. BABYLON.serialize()
  43248. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43249. __decorate([
  43250. BABYLON.serialize()
  43251. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43252. __decorate([
  43253. BABYLON.serialize()
  43254. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43255. __decorate([
  43256. BABYLON.serialize("useLightmapAsShadowmap")
  43257. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43258. __decorate([
  43259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43260. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43261. __decorate([
  43262. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43263. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43264. __decorate([
  43265. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43266. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43267. __decorate([
  43268. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43269. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43270. __decorate([
  43271. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43272. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43273. __decorate([
  43274. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43275. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43276. __decorate([
  43277. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43278. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43279. __decorate([
  43280. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43281. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43282. __decorate([
  43283. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43284. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43285. __decorate([
  43286. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43287. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43288. __decorate([
  43289. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43290. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43291. __decorate([
  43292. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43293. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43294. __decorate([
  43295. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43296. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43297. __decorate([
  43298. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43299. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43300. __decorate([
  43301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43302. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43303. __decorate([
  43304. BABYLON.serialize("maxSimultaneousLights")
  43305. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43306. __decorate([
  43307. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43308. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43309. __decorate([
  43310. BABYLON.serialize("invertNormalMapX")
  43311. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43312. __decorate([
  43313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43314. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43315. __decorate([
  43316. BABYLON.serialize("invertNormalMapY")
  43317. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43318. __decorate([
  43319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43320. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43321. __decorate([
  43322. BABYLON.serialize("twoSidedLighting")
  43323. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43324. __decorate([
  43325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43326. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43327. __decorate([
  43328. BABYLON.serialize()
  43329. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43330. return StandardMaterial;
  43331. }(BABYLON.PushMaterial));
  43332. BABYLON.StandardMaterial = StandardMaterial;
  43333. })(BABYLON || (BABYLON = {}));
  43334. //# sourceMappingURL=babylon.standardMaterial.js.map
  43335. var BABYLON;
  43336. (function (BABYLON) {
  43337. /**
  43338. * Manages the defines for the PBR Material.
  43339. * @hiddenChildren
  43340. */
  43341. var PBRMaterialDefines = /** @class */ (function (_super) {
  43342. __extends(PBRMaterialDefines, _super);
  43343. /**
  43344. * Initializes the PBR Material defines.
  43345. */
  43346. function PBRMaterialDefines() {
  43347. var _this = _super.call(this) || this;
  43348. _this.PBR = true;
  43349. _this.MAINUV1 = false;
  43350. _this.MAINUV2 = false;
  43351. _this.UV1 = false;
  43352. _this.UV2 = false;
  43353. _this.ALBEDO = false;
  43354. _this.ALBEDODIRECTUV = 0;
  43355. _this.VERTEXCOLOR = false;
  43356. _this.AMBIENT = false;
  43357. _this.AMBIENTDIRECTUV = 0;
  43358. _this.AMBIENTINGRAYSCALE = false;
  43359. _this.OPACITY = false;
  43360. _this.VERTEXALPHA = false;
  43361. _this.OPACITYDIRECTUV = 0;
  43362. _this.OPACITYRGB = false;
  43363. _this.ALPHATEST = false;
  43364. _this.DEPTHPREPASS = false;
  43365. _this.ALPHABLEND = false;
  43366. _this.ALPHAFROMALBEDO = false;
  43367. _this.ALPHATESTVALUE = "0.5";
  43368. _this.SPECULAROVERALPHA = false;
  43369. _this.RADIANCEOVERALPHA = false;
  43370. _this.ALPHAFRESNEL = false;
  43371. _this.LINEARALPHAFRESNEL = false;
  43372. _this.PREMULTIPLYALPHA = false;
  43373. _this.EMISSIVE = false;
  43374. _this.EMISSIVEDIRECTUV = 0;
  43375. _this.REFLECTIVITY = false;
  43376. _this.REFLECTIVITYDIRECTUV = 0;
  43377. _this.SPECULARTERM = false;
  43378. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43379. _this.MICROSURFACEAUTOMATIC = false;
  43380. _this.LODBASEDMICROSFURACE = false;
  43381. _this.MICROSURFACEMAP = false;
  43382. _this.MICROSURFACEMAPDIRECTUV = 0;
  43383. _this.METALLICWORKFLOW = false;
  43384. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43385. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43386. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43387. _this.AOSTOREINMETALMAPRED = false;
  43388. _this.ENVIRONMENTBRDF = false;
  43389. _this.NORMAL = false;
  43390. _this.TANGENT = false;
  43391. _this.BUMP = false;
  43392. _this.BUMPDIRECTUV = 0;
  43393. _this.OBJECTSPACE_NORMALMAP = false;
  43394. _this.PARALLAX = false;
  43395. _this.PARALLAXOCCLUSION = false;
  43396. _this.NORMALXYSCALE = true;
  43397. _this.LIGHTMAP = false;
  43398. _this.LIGHTMAPDIRECTUV = 0;
  43399. _this.USELIGHTMAPASSHADOWMAP = false;
  43400. _this.GAMMALIGHTMAP = false;
  43401. _this.REFLECTION = false;
  43402. _this.REFLECTIONMAP_3D = false;
  43403. _this.REFLECTIONMAP_SPHERICAL = false;
  43404. _this.REFLECTIONMAP_PLANAR = false;
  43405. _this.REFLECTIONMAP_CUBIC = false;
  43406. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43407. _this.REFLECTIONMAP_PROJECTION = false;
  43408. _this.REFLECTIONMAP_SKYBOX = false;
  43409. _this.REFLECTIONMAP_EXPLICIT = false;
  43410. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43411. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43412. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43413. _this.INVERTCUBICMAP = false;
  43414. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43415. _this.USESPHERICALINVERTEX = false;
  43416. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43417. _this.LODINREFLECTIONALPHA = false;
  43418. _this.GAMMAREFLECTION = false;
  43419. _this.RGBDREFLECTION = false;
  43420. _this.RADIANCEOCCLUSION = false;
  43421. _this.HORIZONOCCLUSION = false;
  43422. _this.REFRACTION = false;
  43423. _this.REFRACTIONMAP_3D = false;
  43424. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43425. _this.LODINREFRACTIONALPHA = false;
  43426. _this.GAMMAREFRACTION = false;
  43427. _this.RGBDREFRACTION = false;
  43428. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43429. _this.INSTANCES = false;
  43430. _this.NUM_BONE_INFLUENCERS = 0;
  43431. _this.BonesPerMesh = 0;
  43432. _this.NONUNIFORMSCALING = false;
  43433. _this.MORPHTARGETS = false;
  43434. _this.MORPHTARGETS_NORMAL = false;
  43435. _this.MORPHTARGETS_TANGENT = false;
  43436. _this.NUM_MORPH_INFLUENCERS = 0;
  43437. _this.IMAGEPROCESSING = false;
  43438. _this.VIGNETTE = false;
  43439. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43440. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43441. _this.TONEMAPPING = false;
  43442. _this.CONTRAST = false;
  43443. _this.COLORCURVES = false;
  43444. _this.COLORGRADING = false;
  43445. _this.COLORGRADING3D = false;
  43446. _this.SAMPLER3DGREENDEPTH = false;
  43447. _this.SAMPLER3DBGRMAP = false;
  43448. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43449. _this.EXPOSURE = false;
  43450. _this.USEPHYSICALLIGHTFALLOFF = false;
  43451. _this.TWOSIDEDLIGHTING = false;
  43452. _this.SHADOWFLOAT = false;
  43453. _this.CLIPPLANE = false;
  43454. _this.POINTSIZE = false;
  43455. _this.FOG = false;
  43456. _this.LOGARITHMICDEPTH = false;
  43457. _this.FORCENORMALFORWARD = false;
  43458. _this.SPECULARAA = false;
  43459. _this.UNLIT = false;
  43460. _this.rebuild();
  43461. return _this;
  43462. }
  43463. /**
  43464. * Resets the PBR Material defines.
  43465. */
  43466. PBRMaterialDefines.prototype.reset = function () {
  43467. _super.prototype.reset.call(this);
  43468. this.ALPHATESTVALUE = "0.5";
  43469. this.PBR = true;
  43470. };
  43471. return PBRMaterialDefines;
  43472. }(BABYLON.MaterialDefines));
  43473. /**
  43474. * The Physically based material base class of BJS.
  43475. *
  43476. * This offers the main features of a standard PBR material.
  43477. * For more information, please refer to the documentation :
  43478. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43479. */
  43480. var PBRBaseMaterial = /** @class */ (function (_super) {
  43481. __extends(PBRBaseMaterial, _super);
  43482. /**
  43483. * Instantiates a new PBRMaterial instance.
  43484. *
  43485. * @param name The material name
  43486. * @param scene The scene the material will be use in.
  43487. */
  43488. function PBRBaseMaterial(name, scene) {
  43489. var _this = _super.call(this, name, scene) || this;
  43490. /**
  43491. * Intensity of the direct lights e.g. the four lights available in your scene.
  43492. * This impacts both the direct diffuse and specular highlights.
  43493. */
  43494. _this._directIntensity = 1.0;
  43495. /**
  43496. * Intensity of the emissive part of the material.
  43497. * This helps controlling the emissive effect without modifying the emissive color.
  43498. */
  43499. _this._emissiveIntensity = 1.0;
  43500. /**
  43501. * Intensity of the environment e.g. how much the environment will light the object
  43502. * either through harmonics for rough material or through the refelction for shiny ones.
  43503. */
  43504. _this._environmentIntensity = 1.0;
  43505. /**
  43506. * This is a special control allowing the reduction of the specular highlights coming from the
  43507. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43508. */
  43509. _this._specularIntensity = 1.0;
  43510. /**
  43511. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43512. */
  43513. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43514. /**
  43515. * Debug Control allowing disabling the bump map on this material.
  43516. */
  43517. _this._disableBumpMap = false;
  43518. /**
  43519. * AKA Occlusion Texture Intensity in other nomenclature.
  43520. */
  43521. _this._ambientTextureStrength = 1.0;
  43522. /**
  43523. * The color of a material in ambient lighting.
  43524. */
  43525. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43526. /**
  43527. * AKA Diffuse Color in other nomenclature.
  43528. */
  43529. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43530. /**
  43531. * AKA Specular Color in other nomenclature.
  43532. */
  43533. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43534. /**
  43535. * The color applied when light is reflected from a material.
  43536. */
  43537. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43538. /**
  43539. * The color applied when light is emitted from a material.
  43540. */
  43541. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43542. /**
  43543. * AKA Glossiness in other nomenclature.
  43544. */
  43545. _this._microSurface = 0.9;
  43546. /**
  43547. * source material index of refraction (IOR)' / 'destination material IOR.
  43548. */
  43549. _this._indexOfRefraction = 0.66;
  43550. /**
  43551. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43552. */
  43553. _this._invertRefractionY = false;
  43554. /**
  43555. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43556. * Materials half opaque for instance using refraction could benefit from this control.
  43557. */
  43558. _this._linkRefractionWithTransparency = false;
  43559. /**
  43560. * Specifies that the material will use the light map as a show map.
  43561. */
  43562. _this._useLightmapAsShadowmap = false;
  43563. /**
  43564. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43565. * makes the reflect vector face the model (under horizon).
  43566. */
  43567. _this._useHorizonOcclusion = true;
  43568. /**
  43569. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43570. * too much the area relying on ambient texture to define their ambient occlusion.
  43571. */
  43572. _this._useRadianceOcclusion = true;
  43573. /**
  43574. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43575. */
  43576. _this._useAlphaFromAlbedoTexture = false;
  43577. /**
  43578. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43579. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43580. */
  43581. _this._useSpecularOverAlpha = true;
  43582. /**
  43583. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43584. */
  43585. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43586. /**
  43587. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43588. */
  43589. _this._useRoughnessFromMetallicTextureAlpha = true;
  43590. /**
  43591. * Specifies if the metallic texture contains the roughness information in its green channel.
  43592. */
  43593. _this._useRoughnessFromMetallicTextureGreen = false;
  43594. /**
  43595. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43596. */
  43597. _this._useMetallnessFromMetallicTextureBlue = false;
  43598. /**
  43599. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43600. */
  43601. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43602. /**
  43603. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43604. */
  43605. _this._useAmbientInGrayScale = false;
  43606. /**
  43607. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43608. * The material will try to infer what glossiness each pixel should be.
  43609. */
  43610. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43611. /**
  43612. * BJS is using an harcoded light falloff based on a manually sets up range.
  43613. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43614. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43615. */
  43616. _this._usePhysicalLightFalloff = true;
  43617. /**
  43618. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43619. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43620. */
  43621. _this._useRadianceOverAlpha = true;
  43622. /**
  43623. * Allows using an object space normal map (instead of tangent space).
  43624. */
  43625. _this._useObjectSpaceNormalMap = false;
  43626. /**
  43627. * Allows using the bump map in parallax mode.
  43628. */
  43629. _this._useParallax = false;
  43630. /**
  43631. * Allows using the bump map in parallax occlusion mode.
  43632. */
  43633. _this._useParallaxOcclusion = false;
  43634. /**
  43635. * Controls the scale bias of the parallax mode.
  43636. */
  43637. _this._parallaxScaleBias = 0.05;
  43638. /**
  43639. * If sets to true, disables all the lights affecting the material.
  43640. */
  43641. _this._disableLighting = false;
  43642. /**
  43643. * Number of Simultaneous lights allowed on the material.
  43644. */
  43645. _this._maxSimultaneousLights = 4;
  43646. /**
  43647. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43648. */
  43649. _this._invertNormalMapX = false;
  43650. /**
  43651. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43652. */
  43653. _this._invertNormalMapY = false;
  43654. /**
  43655. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43656. */
  43657. _this._twoSidedLighting = false;
  43658. /**
  43659. * Defines the alpha limits in alpha test mode.
  43660. */
  43661. _this._alphaCutOff = 0.4;
  43662. /**
  43663. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43664. */
  43665. _this._forceAlphaTest = false;
  43666. /**
  43667. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43668. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43669. */
  43670. _this._useAlphaFresnel = false;
  43671. /**
  43672. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43673. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43674. */
  43675. _this._useLinearAlphaFresnel = false;
  43676. /**
  43677. * The transparency mode of the material.
  43678. */
  43679. _this._transparencyMode = null;
  43680. /**
  43681. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43682. * from cos thetav and roughness:
  43683. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43684. */
  43685. _this._environmentBRDFTexture = null;
  43686. /**
  43687. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43688. */
  43689. _this._forceIrradianceInFragment = false;
  43690. /**
  43691. * Force normal to face away from face.
  43692. */
  43693. _this._forceNormalForward = false;
  43694. /**
  43695. * Enables specular anti aliasing in the PBR shader.
  43696. * It will both interacts on the Geometry for analytical and IBL lighting.
  43697. * It also prefilter the roughness map based on the bump values.
  43698. */
  43699. _this._enableSpecularAntiAliasing = false;
  43700. /**
  43701. * Stores the available render targets.
  43702. */
  43703. _this._renderTargets = new BABYLON.SmartArray(16);
  43704. /**
  43705. * Sets the global ambient color for the material used in lighting calculations.
  43706. */
  43707. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43708. /**
  43709. * If set to true, no lighting calculations will be applied.
  43710. */
  43711. _this._unlit = false;
  43712. // Setup the default processing configuration to the scene.
  43713. _this._attachImageProcessingConfiguration(null);
  43714. _this.getRenderTargetTextures = function () {
  43715. _this._renderTargets.reset();
  43716. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43717. _this._renderTargets.push(_this._reflectionTexture);
  43718. }
  43719. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43720. _this._renderTargets.push(_this._refractionTexture);
  43721. }
  43722. return _this._renderTargets;
  43723. };
  43724. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43725. return _this;
  43726. }
  43727. /**
  43728. * Attaches a new image processing configuration to the PBR Material.
  43729. * @param configuration
  43730. */
  43731. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43732. var _this = this;
  43733. if (configuration === this._imageProcessingConfiguration) {
  43734. return;
  43735. }
  43736. // Detaches observer.
  43737. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43738. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43739. }
  43740. // Pick the scene configuration if needed.
  43741. if (!configuration) {
  43742. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43743. }
  43744. else {
  43745. this._imageProcessingConfiguration = configuration;
  43746. }
  43747. // Attaches observer.
  43748. if (this._imageProcessingConfiguration) {
  43749. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43750. _this._markAllSubMeshesAsImageProcessingDirty();
  43751. });
  43752. }
  43753. };
  43754. /**
  43755. * Gets the name of the material class.
  43756. */
  43757. PBRBaseMaterial.prototype.getClassName = function () {
  43758. return "PBRBaseMaterial";
  43759. };
  43760. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43761. /**
  43762. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43763. */
  43764. get: function () {
  43765. return this._useLogarithmicDepth;
  43766. },
  43767. /**
  43768. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43769. */
  43770. set: function (value) {
  43771. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43772. },
  43773. enumerable: true,
  43774. configurable: true
  43775. });
  43776. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43777. /**
  43778. * Gets the current transparency mode.
  43779. */
  43780. get: function () {
  43781. return this._transparencyMode;
  43782. },
  43783. /**
  43784. * Sets the transparency mode of the material.
  43785. *
  43786. * | Value | Type | Description |
  43787. * | ----- | ----------------------------------- | ----------- |
  43788. * | 0 | OPAQUE | |
  43789. * | 1 | ALPHATEST | |
  43790. * | 2 | ALPHABLEND | |
  43791. * | 3 | ALPHATESTANDBLEND | |
  43792. *
  43793. */
  43794. set: function (value) {
  43795. if (this._transparencyMode === value) {
  43796. return;
  43797. }
  43798. this._transparencyMode = value;
  43799. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43800. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43801. },
  43802. enumerable: true,
  43803. configurable: true
  43804. });
  43805. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43806. /**
  43807. * Returns true if alpha blending should be disabled.
  43808. */
  43809. get: function () {
  43810. return (this._linkRefractionWithTransparency ||
  43811. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43812. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43813. },
  43814. enumerable: true,
  43815. configurable: true
  43816. });
  43817. /**
  43818. * Specifies whether or not this material should be rendered in alpha blend mode.
  43819. */
  43820. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43821. if (this._disableAlphaBlending) {
  43822. return false;
  43823. }
  43824. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43825. };
  43826. /**
  43827. * Specifies if the mesh will require alpha blending.
  43828. * @param mesh - BJS mesh.
  43829. */
  43830. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43831. if (this._disableAlphaBlending) {
  43832. return false;
  43833. }
  43834. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43835. };
  43836. /**
  43837. * Specifies whether or not this material should be rendered in alpha test mode.
  43838. */
  43839. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43840. if (this._forceAlphaTest) {
  43841. return true;
  43842. }
  43843. if (this._linkRefractionWithTransparency) {
  43844. return false;
  43845. }
  43846. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43847. };
  43848. /**
  43849. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43850. */
  43851. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43852. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43853. };
  43854. /**
  43855. * Gets the texture used for the alpha test.
  43856. */
  43857. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43858. return this._albedoTexture;
  43859. };
  43860. /**
  43861. * Specifies that the submesh is ready to be used.
  43862. * @param mesh - BJS mesh.
  43863. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43864. * @param useInstances - Specifies that instances should be used.
  43865. * @returns - boolean indicating that the submesh is ready or not.
  43866. */
  43867. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43868. if (subMesh.effect && this.isFrozen) {
  43869. if (this._wasPreviouslyReady) {
  43870. return true;
  43871. }
  43872. }
  43873. if (!subMesh._materialDefines) {
  43874. subMesh._materialDefines = new PBRMaterialDefines();
  43875. }
  43876. var defines = subMesh._materialDefines;
  43877. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43878. if (defines._renderId === this.getScene().getRenderId()) {
  43879. return true;
  43880. }
  43881. }
  43882. var scene = this.getScene();
  43883. var engine = scene.getEngine();
  43884. if (defines._areTexturesDirty) {
  43885. if (scene.texturesEnabled) {
  43886. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43887. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43888. return false;
  43889. }
  43890. }
  43891. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43892. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43893. return false;
  43894. }
  43895. }
  43896. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43897. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43898. return false;
  43899. }
  43900. }
  43901. var reflectionTexture = this._getReflectionTexture();
  43902. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43903. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43904. return false;
  43905. }
  43906. }
  43907. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43908. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43909. return false;
  43910. }
  43911. }
  43912. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43913. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43914. return false;
  43915. }
  43916. }
  43917. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43918. if (this._metallicTexture) {
  43919. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43920. return false;
  43921. }
  43922. }
  43923. else if (this._reflectivityTexture) {
  43924. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43925. return false;
  43926. }
  43927. }
  43928. if (this._microSurfaceTexture) {
  43929. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43930. return false;
  43931. }
  43932. }
  43933. }
  43934. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43935. // Bump texture cannot be not blocking.
  43936. if (!this._bumpTexture.isReady()) {
  43937. return false;
  43938. }
  43939. }
  43940. var refractionTexture = this._getRefractionTexture();
  43941. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43942. if (!refractionTexture.isReadyOrNotBlocking()) {
  43943. return false;
  43944. }
  43945. }
  43946. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43947. // This is blocking.
  43948. if (!this._environmentBRDFTexture.isReady()) {
  43949. return false;
  43950. }
  43951. }
  43952. }
  43953. }
  43954. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43955. if (!this._imageProcessingConfiguration.isReady()) {
  43956. return false;
  43957. }
  43958. }
  43959. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43960. mesh.createNormals(true);
  43961. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43962. }
  43963. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43964. if (effect) {
  43965. scene.resetCachedMaterial();
  43966. subMesh.setEffect(effect, defines);
  43967. this.buildUniformLayout();
  43968. }
  43969. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43970. return false;
  43971. }
  43972. defines._renderId = scene.getRenderId();
  43973. this._wasPreviouslyReady = true;
  43974. return true;
  43975. };
  43976. /**
  43977. * Specifies if the material uses metallic roughness workflow.
  43978. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43979. */
  43980. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43981. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43982. return true;
  43983. }
  43984. return false;
  43985. };
  43986. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43987. if (onCompiled === void 0) { onCompiled = null; }
  43988. if (onError === void 0) { onError = null; }
  43989. if (useInstances === void 0) { useInstances = null; }
  43990. if (useClipPlane === void 0) { useClipPlane = null; }
  43991. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43992. if (!defines.isDirty) {
  43993. return null;
  43994. }
  43995. defines.markAsProcessed();
  43996. var scene = this.getScene();
  43997. var engine = scene.getEngine();
  43998. // Fallbacks
  43999. var fallbacks = new BABYLON.EffectFallbacks();
  44000. var fallbackRank = 0;
  44001. if (defines.USESPHERICALINVERTEX) {
  44002. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44003. }
  44004. if (defines.FOG) {
  44005. fallbacks.addFallback(fallbackRank, "FOG");
  44006. }
  44007. if (defines.SPECULARAA) {
  44008. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44009. }
  44010. if (defines.POINTSIZE) {
  44011. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44012. }
  44013. if (defines.LOGARITHMICDEPTH) {
  44014. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44015. }
  44016. if (defines.PARALLAX) {
  44017. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44018. }
  44019. if (defines.PARALLAXOCCLUSION) {
  44020. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44021. }
  44022. if (defines.ENVIRONMENTBRDF) {
  44023. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44024. }
  44025. if (defines.TANGENT) {
  44026. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44027. }
  44028. if (defines.BUMP) {
  44029. fallbacks.addFallback(fallbackRank++, "BUMP");
  44030. }
  44031. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44032. if (defines.SPECULARTERM) {
  44033. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44034. }
  44035. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44036. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44037. }
  44038. if (defines.LIGHTMAP) {
  44039. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44040. }
  44041. if (defines.NORMAL) {
  44042. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44043. }
  44044. if (defines.AMBIENT) {
  44045. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44046. }
  44047. if (defines.EMISSIVE) {
  44048. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44049. }
  44050. if (defines.VERTEXCOLOR) {
  44051. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44052. }
  44053. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44054. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44055. }
  44056. if (defines.MORPHTARGETS) {
  44057. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44058. }
  44059. //Attributes
  44060. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44061. if (defines.NORMAL) {
  44062. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44063. }
  44064. if (defines.TANGENT) {
  44065. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44066. }
  44067. if (defines.UV1) {
  44068. attribs.push(BABYLON.VertexBuffer.UVKind);
  44069. }
  44070. if (defines.UV2) {
  44071. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44072. }
  44073. if (defines.VERTEXCOLOR) {
  44074. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44075. }
  44076. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44077. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44078. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44079. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44080. "vFogInfos", "vFogColor", "pointSize",
  44081. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44082. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44083. "mBones",
  44084. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44085. "vLightingIntensity",
  44086. "logarithmicDepthConstant",
  44087. "vSphericalX", "vSphericalY", "vSphericalZ",
  44088. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44089. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44090. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44091. "vTangentSpaceParams"
  44092. ];
  44093. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44094. "bumpSampler", "lightmapSampler", "opacitySampler",
  44095. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44096. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44097. "microSurfaceSampler", "environmentBrdfSampler"];
  44098. var uniformBuffers = ["Material", "Scene"];
  44099. if (BABYLON.ImageProcessingConfiguration) {
  44100. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44101. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44102. }
  44103. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44104. uniformsNames: uniforms,
  44105. uniformBuffersNames: uniformBuffers,
  44106. samplers: samplers,
  44107. defines: defines,
  44108. maxSimultaneousLights: this._maxSimultaneousLights
  44109. });
  44110. var join = defines.toString();
  44111. return engine.createEffect("pbr", {
  44112. attributes: attribs,
  44113. uniformsNames: uniforms,
  44114. uniformBuffersNames: uniformBuffers,
  44115. samplers: samplers,
  44116. defines: join,
  44117. fallbacks: fallbacks,
  44118. onCompiled: onCompiled,
  44119. onError: onError,
  44120. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44121. }, engine);
  44122. };
  44123. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44124. if (useInstances === void 0) { useInstances = null; }
  44125. if (useClipPlane === void 0) { useClipPlane = null; }
  44126. var scene = this.getScene();
  44127. var engine = scene.getEngine();
  44128. // Lights
  44129. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44130. defines._needNormals = true;
  44131. // Textures
  44132. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44133. if (defines._areTexturesDirty) {
  44134. defines._needUVs = false;
  44135. if (scene.texturesEnabled) {
  44136. if (scene.getEngine().getCaps().textureLOD) {
  44137. defines.LODBASEDMICROSFURACE = true;
  44138. }
  44139. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44140. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44141. }
  44142. else {
  44143. defines.ALBEDO = false;
  44144. }
  44145. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44146. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44147. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44148. }
  44149. else {
  44150. defines.AMBIENT = false;
  44151. }
  44152. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44153. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44154. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44155. }
  44156. else {
  44157. defines.OPACITY = false;
  44158. }
  44159. var reflectionTexture = this._getReflectionTexture();
  44160. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44161. defines.REFLECTION = true;
  44162. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44163. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44164. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44165. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44166. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44167. defines.INVERTCUBICMAP = true;
  44168. }
  44169. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44170. switch (reflectionTexture.coordinatesMode) {
  44171. case BABYLON.Texture.EXPLICIT_MODE:
  44172. defines.REFLECTIONMAP_EXPLICIT = true;
  44173. break;
  44174. case BABYLON.Texture.PLANAR_MODE:
  44175. defines.REFLECTIONMAP_PLANAR = true;
  44176. break;
  44177. case BABYLON.Texture.PROJECTION_MODE:
  44178. defines.REFLECTIONMAP_PROJECTION = true;
  44179. break;
  44180. case BABYLON.Texture.SKYBOX_MODE:
  44181. defines.REFLECTIONMAP_SKYBOX = true;
  44182. break;
  44183. case BABYLON.Texture.SPHERICAL_MODE:
  44184. defines.REFLECTIONMAP_SPHERICAL = true;
  44185. break;
  44186. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44187. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44188. break;
  44189. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44190. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44191. break;
  44192. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44193. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44194. break;
  44195. case BABYLON.Texture.CUBIC_MODE:
  44196. case BABYLON.Texture.INVCUBIC_MODE:
  44197. default:
  44198. defines.REFLECTIONMAP_CUBIC = true;
  44199. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44200. break;
  44201. }
  44202. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44203. if (reflectionTexture.sphericalPolynomial) {
  44204. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44205. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44206. defines.USESPHERICALINVERTEX = false;
  44207. }
  44208. else {
  44209. defines.USESPHERICALINVERTEX = true;
  44210. }
  44211. }
  44212. }
  44213. }
  44214. else {
  44215. defines.REFLECTION = false;
  44216. defines.REFLECTIONMAP_3D = false;
  44217. defines.REFLECTIONMAP_SPHERICAL = false;
  44218. defines.REFLECTIONMAP_PLANAR = false;
  44219. defines.REFLECTIONMAP_CUBIC = false;
  44220. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44221. defines.REFLECTIONMAP_PROJECTION = false;
  44222. defines.REFLECTIONMAP_SKYBOX = false;
  44223. defines.REFLECTIONMAP_EXPLICIT = false;
  44224. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44225. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44226. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44227. defines.INVERTCUBICMAP = false;
  44228. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44229. defines.USESPHERICALINVERTEX = false;
  44230. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44231. defines.LODINREFLECTIONALPHA = false;
  44232. defines.GAMMAREFLECTION = false;
  44233. defines.RGBDREFLECTION = false;
  44234. }
  44235. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44236. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44237. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44238. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44239. }
  44240. else {
  44241. defines.LIGHTMAP = false;
  44242. }
  44243. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44244. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44245. }
  44246. else {
  44247. defines.EMISSIVE = false;
  44248. }
  44249. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44250. if (this._metallicTexture) {
  44251. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44252. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44253. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44254. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44255. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44256. }
  44257. else if (this._reflectivityTexture) {
  44258. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44259. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44260. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44261. }
  44262. else {
  44263. defines.REFLECTIVITY = false;
  44264. }
  44265. if (this._microSurfaceTexture) {
  44266. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44267. }
  44268. else {
  44269. defines.MICROSURFACEMAP = false;
  44270. }
  44271. }
  44272. else {
  44273. defines.REFLECTIVITY = false;
  44274. defines.MICROSURFACEMAP = false;
  44275. }
  44276. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44277. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44278. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44279. defines.PARALLAX = true;
  44280. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44281. }
  44282. else {
  44283. defines.PARALLAX = false;
  44284. }
  44285. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44286. }
  44287. else {
  44288. defines.BUMP = false;
  44289. }
  44290. var refractionTexture = this._getRefractionTexture();
  44291. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44292. defines.REFRACTION = true;
  44293. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44294. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44295. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44296. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44297. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44298. if (this._linkRefractionWithTransparency) {
  44299. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44300. }
  44301. }
  44302. else {
  44303. defines.REFRACTION = false;
  44304. }
  44305. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44306. defines.ENVIRONMENTBRDF = true;
  44307. }
  44308. else {
  44309. defines.ENVIRONMENTBRDF = false;
  44310. }
  44311. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44312. defines.ALPHAFROMALBEDO = true;
  44313. }
  44314. else {
  44315. defines.ALPHAFROMALBEDO = false;
  44316. }
  44317. }
  44318. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44319. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44320. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44321. if (!this.backFaceCulling && this._twoSidedLighting) {
  44322. defines.TWOSIDEDLIGHTING = true;
  44323. }
  44324. else {
  44325. defines.TWOSIDEDLIGHTING = false;
  44326. }
  44327. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44328. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44329. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44330. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44331. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44332. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44333. }
  44334. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44335. this._imageProcessingConfiguration.prepareDefines(defines);
  44336. }
  44337. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44338. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44339. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44340. // Misc.
  44341. if (defines._areMiscDirty) {
  44342. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44343. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44344. }
  44345. // Values that need to be evaluated on every frame
  44346. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44347. // Attribs
  44348. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44349. };
  44350. /**
  44351. * Force shader compilation
  44352. */
  44353. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44354. var _this = this;
  44355. var localOptions = __assign({ clipPlane: false }, options);
  44356. var defines = new PBRMaterialDefines();
  44357. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44358. if (effect.isReady()) {
  44359. if (onCompiled) {
  44360. onCompiled(this);
  44361. }
  44362. }
  44363. else {
  44364. effect.onCompileObservable.add(function () {
  44365. if (onCompiled) {
  44366. onCompiled(_this);
  44367. }
  44368. });
  44369. }
  44370. };
  44371. /**
  44372. * Initializes the uniform buffer layout for the shader.
  44373. */
  44374. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44375. // Order is important !
  44376. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44377. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44378. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44379. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44380. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44381. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44382. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44383. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44384. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44385. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44386. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44387. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44388. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44389. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44390. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44391. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44392. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44393. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44394. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44395. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44396. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44397. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44398. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44399. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44400. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44401. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44402. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44403. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44404. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44405. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44406. this._uniformBuffer.addUniform("pointSize", 1);
  44407. this._uniformBuffer.create();
  44408. };
  44409. /**
  44410. * Unbinds the textures.
  44411. */
  44412. PBRBaseMaterial.prototype.unbind = function () {
  44413. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44414. this._uniformBuffer.setTexture("reflectionSampler", null);
  44415. }
  44416. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44417. this._uniformBuffer.setTexture("refractionSampler", null);
  44418. }
  44419. _super.prototype.unbind.call(this);
  44420. };
  44421. /**
  44422. * Binds the submesh data.
  44423. * @param world - The world matrix.
  44424. * @param mesh - The BJS mesh.
  44425. * @param subMesh - A submesh of the BJS mesh.
  44426. */
  44427. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44428. var scene = this.getScene();
  44429. var defines = subMesh._materialDefines;
  44430. if (!defines) {
  44431. return;
  44432. }
  44433. var effect = subMesh.effect;
  44434. if (!effect) {
  44435. return;
  44436. }
  44437. this._activeEffect = effect;
  44438. // Matrices
  44439. this.bindOnlyWorldMatrix(world);
  44440. // Normal Matrix
  44441. if (defines.OBJECTSPACE_NORMALMAP) {
  44442. world.toNormalMatrix(this._normalMatrix);
  44443. this.bindOnlyNormalMatrix(this._normalMatrix);
  44444. }
  44445. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44446. // Bones
  44447. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44448. var reflectionTexture = null;
  44449. if (mustRebind) {
  44450. this._uniformBuffer.bindToEffect(effect, "Material");
  44451. this.bindViewProjection(effect);
  44452. reflectionTexture = this._getReflectionTexture();
  44453. var refractionTexture = this._getRefractionTexture();
  44454. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44455. // Texture uniforms
  44456. if (scene.texturesEnabled) {
  44457. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44458. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44459. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44460. }
  44461. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44462. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44463. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44464. }
  44465. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44466. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44467. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44468. }
  44469. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44470. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44471. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44472. if (reflectionTexture.boundingBoxSize) {
  44473. var cubeTexture = reflectionTexture;
  44474. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44475. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44476. }
  44477. var polynomials = reflectionTexture.sphericalPolynomial;
  44478. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44479. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44480. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44481. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44482. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44483. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44484. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44485. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44486. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44487. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44488. }
  44489. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44490. }
  44491. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44492. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44493. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44494. }
  44495. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44496. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44497. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44498. }
  44499. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44500. if (this._metallicTexture) {
  44501. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44502. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44503. }
  44504. else if (this._reflectivityTexture) {
  44505. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44506. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44507. }
  44508. if (this._microSurfaceTexture) {
  44509. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44510. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44511. }
  44512. }
  44513. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44514. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44515. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44516. if (scene._mirroredCameraPosition) {
  44517. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44518. }
  44519. else {
  44520. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44521. }
  44522. }
  44523. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44524. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44525. var depth = 1.0;
  44526. if (!refractionTexture.isCube) {
  44527. if (refractionTexture.depth) {
  44528. depth = refractionTexture.depth;
  44529. }
  44530. }
  44531. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44532. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44533. }
  44534. }
  44535. // Point size
  44536. if (this.pointsCloud) {
  44537. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44538. }
  44539. // Colors
  44540. if (defines.METALLICWORKFLOW) {
  44541. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44542. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44543. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44544. }
  44545. else {
  44546. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44547. }
  44548. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44549. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44550. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44551. // Misc
  44552. this._lightingInfos.x = this._directIntensity;
  44553. this._lightingInfos.y = this._emissiveIntensity;
  44554. this._lightingInfos.z = this._environmentIntensity;
  44555. this._lightingInfos.w = this._specularIntensity;
  44556. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44557. }
  44558. // Textures
  44559. if (scene.texturesEnabled) {
  44560. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44561. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44562. }
  44563. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44564. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44565. }
  44566. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44567. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44568. }
  44569. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44570. if (defines.LODBASEDMICROSFURACE) {
  44571. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44572. }
  44573. else {
  44574. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44575. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44576. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44577. }
  44578. }
  44579. if (defines.ENVIRONMENTBRDF) {
  44580. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44581. }
  44582. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44583. if (defines.LODBASEDMICROSFURACE) {
  44584. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44585. }
  44586. else {
  44587. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44588. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44589. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44590. }
  44591. }
  44592. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44593. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44594. }
  44595. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44596. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44597. }
  44598. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44599. if (this._metallicTexture) {
  44600. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44601. }
  44602. else if (this._reflectivityTexture) {
  44603. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44604. }
  44605. if (this._microSurfaceTexture) {
  44606. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44607. }
  44608. }
  44609. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44610. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44611. }
  44612. }
  44613. // Clip plane
  44614. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44615. // Colors
  44616. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44617. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44618. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44619. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44620. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44621. }
  44622. if (mustRebind || !this.isFrozen) {
  44623. // Lights
  44624. if (scene.lightsEnabled && !this._disableLighting) {
  44625. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44626. }
  44627. // View
  44628. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44629. this.bindView(effect);
  44630. }
  44631. // Fog
  44632. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44633. // Morph targets
  44634. if (defines.NUM_MORPH_INFLUENCERS) {
  44635. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44636. }
  44637. // image processing
  44638. this._imageProcessingConfiguration.bind(this._activeEffect);
  44639. // Log. depth
  44640. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44641. }
  44642. this._uniformBuffer.update();
  44643. this._afterBind(mesh, this._activeEffect);
  44644. };
  44645. /**
  44646. * Returns the animatable textures.
  44647. * @returns - Array of animatable textures.
  44648. */
  44649. PBRBaseMaterial.prototype.getAnimatables = function () {
  44650. var results = [];
  44651. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44652. results.push(this._albedoTexture);
  44653. }
  44654. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44655. results.push(this._ambientTexture);
  44656. }
  44657. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44658. results.push(this._opacityTexture);
  44659. }
  44660. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44661. results.push(this._reflectionTexture);
  44662. }
  44663. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44664. results.push(this._emissiveTexture);
  44665. }
  44666. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44667. results.push(this._metallicTexture);
  44668. }
  44669. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44670. results.push(this._reflectivityTexture);
  44671. }
  44672. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44673. results.push(this._bumpTexture);
  44674. }
  44675. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44676. results.push(this._lightmapTexture);
  44677. }
  44678. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44679. results.push(this._refractionTexture);
  44680. }
  44681. return results;
  44682. };
  44683. /**
  44684. * Returns the texture used for reflections.
  44685. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44686. */
  44687. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44688. if (this._reflectionTexture) {
  44689. return this._reflectionTexture;
  44690. }
  44691. return this.getScene().environmentTexture;
  44692. };
  44693. /**
  44694. * Returns the texture used for refraction or null if none is used.
  44695. * @returns - Refection texture if present. If no refraction texture and refraction
  44696. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44697. */
  44698. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44699. if (this._refractionTexture) {
  44700. return this._refractionTexture;
  44701. }
  44702. if (this._linkRefractionWithTransparency) {
  44703. return this.getScene().environmentTexture;
  44704. }
  44705. return null;
  44706. };
  44707. /**
  44708. * Disposes the resources of the material.
  44709. * @param forceDisposeEffect - Forces the disposal of effects.
  44710. * @param forceDisposeTextures - Forces the disposal of all textures.
  44711. */
  44712. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44713. if (forceDisposeTextures) {
  44714. if (this._albedoTexture) {
  44715. this._albedoTexture.dispose();
  44716. }
  44717. if (this._ambientTexture) {
  44718. this._ambientTexture.dispose();
  44719. }
  44720. if (this._opacityTexture) {
  44721. this._opacityTexture.dispose();
  44722. }
  44723. if (this._reflectionTexture) {
  44724. this._reflectionTexture.dispose();
  44725. }
  44726. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44727. this._environmentBRDFTexture.dispose();
  44728. }
  44729. if (this._emissiveTexture) {
  44730. this._emissiveTexture.dispose();
  44731. }
  44732. if (this._metallicTexture) {
  44733. this._metallicTexture.dispose();
  44734. }
  44735. if (this._reflectivityTexture) {
  44736. this._reflectivityTexture.dispose();
  44737. }
  44738. if (this._bumpTexture) {
  44739. this._bumpTexture.dispose();
  44740. }
  44741. if (this._lightmapTexture) {
  44742. this._lightmapTexture.dispose();
  44743. }
  44744. if (this._refractionTexture) {
  44745. this._refractionTexture.dispose();
  44746. }
  44747. }
  44748. this._renderTargets.dispose();
  44749. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44750. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44751. }
  44752. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44753. };
  44754. /**
  44755. * Stores the reflectivity values based on metallic roughness workflow.
  44756. */
  44757. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44758. __decorate([
  44759. BABYLON.serializeAsImageProcessingConfiguration()
  44760. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44761. __decorate([
  44762. BABYLON.serialize()
  44763. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44764. __decorate([
  44765. BABYLON.serialize()
  44766. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44767. return PBRBaseMaterial;
  44768. }(BABYLON.PushMaterial));
  44769. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44770. })(BABYLON || (BABYLON = {}));
  44771. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44772. var BABYLON;
  44773. (function (BABYLON) {
  44774. /**
  44775. * The Physically based simple base material of BJS.
  44776. *
  44777. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44778. * It is used as the base class for both the specGloss and metalRough conventions.
  44779. */
  44780. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44781. __extends(PBRBaseSimpleMaterial, _super);
  44782. /**
  44783. * Instantiates a new PBRMaterial instance.
  44784. *
  44785. * @param name The material name
  44786. * @param scene The scene the material will be use in.
  44787. */
  44788. function PBRBaseSimpleMaterial(name, scene) {
  44789. var _this = _super.call(this, name, scene) || this;
  44790. /**
  44791. * Number of Simultaneous lights allowed on the material.
  44792. */
  44793. _this.maxSimultaneousLights = 4;
  44794. /**
  44795. * If sets to true, disables all the lights affecting the material.
  44796. */
  44797. _this.disableLighting = false;
  44798. /**
  44799. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44800. */
  44801. _this.invertNormalMapX = false;
  44802. /**
  44803. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44804. */
  44805. _this.invertNormalMapY = false;
  44806. /**
  44807. * Emissivie color used to self-illuminate the model.
  44808. */
  44809. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44810. /**
  44811. * Occlusion Channel Strenght.
  44812. */
  44813. _this.occlusionStrength = 1.0;
  44814. _this.useLightmapAsShadowmap = false;
  44815. _this._useAlphaFromAlbedoTexture = true;
  44816. _this._useAmbientInGrayScale = true;
  44817. return _this;
  44818. }
  44819. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44820. /**
  44821. * Gets the current double sided mode.
  44822. */
  44823. get: function () {
  44824. return this._twoSidedLighting;
  44825. },
  44826. /**
  44827. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44828. */
  44829. set: function (value) {
  44830. if (this._twoSidedLighting === value) {
  44831. return;
  44832. }
  44833. this._twoSidedLighting = value;
  44834. this.backFaceCulling = !value;
  44835. this._markAllSubMeshesAsTexturesDirty();
  44836. },
  44837. enumerable: true,
  44838. configurable: true
  44839. });
  44840. /**
  44841. * Return the active textures of the material.
  44842. */
  44843. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44844. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44845. if (this.environmentTexture) {
  44846. activeTextures.push(this.environmentTexture);
  44847. }
  44848. if (this.normalTexture) {
  44849. activeTextures.push(this.normalTexture);
  44850. }
  44851. if (this.emissiveTexture) {
  44852. activeTextures.push(this.emissiveTexture);
  44853. }
  44854. if (this.occlusionTexture) {
  44855. activeTextures.push(this.occlusionTexture);
  44856. }
  44857. if (this.lightmapTexture) {
  44858. activeTextures.push(this.lightmapTexture);
  44859. }
  44860. return activeTextures;
  44861. };
  44862. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44863. if (_super.prototype.hasTexture.call(this, texture)) {
  44864. return true;
  44865. }
  44866. if (this.lightmapTexture === texture) {
  44867. return true;
  44868. }
  44869. return false;
  44870. };
  44871. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44872. return "PBRBaseSimpleMaterial";
  44873. };
  44874. __decorate([
  44875. BABYLON.serialize(),
  44876. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44877. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44878. __decorate([
  44879. BABYLON.serialize(),
  44880. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44881. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44882. __decorate([
  44883. BABYLON.serializeAsTexture(),
  44884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44885. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44886. __decorate([
  44887. BABYLON.serialize(),
  44888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44889. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44890. __decorate([
  44891. BABYLON.serialize(),
  44892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44893. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44894. __decorate([
  44895. BABYLON.serializeAsTexture(),
  44896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44897. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44898. __decorate([
  44899. BABYLON.serializeAsColor3("emissive"),
  44900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44901. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44902. __decorate([
  44903. BABYLON.serializeAsTexture(),
  44904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44905. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44906. __decorate([
  44907. BABYLON.serialize(),
  44908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44909. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44910. __decorate([
  44911. BABYLON.serializeAsTexture(),
  44912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44913. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44914. __decorate([
  44915. BABYLON.serialize(),
  44916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44917. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44918. __decorate([
  44919. BABYLON.serialize()
  44920. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44921. __decorate([
  44922. BABYLON.serializeAsTexture(),
  44923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44924. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44925. __decorate([
  44926. BABYLON.serialize(),
  44927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44928. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44929. return PBRBaseSimpleMaterial;
  44930. }(BABYLON.PBRBaseMaterial));
  44931. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44932. })(BABYLON || (BABYLON = {}));
  44933. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44934. var BABYLON;
  44935. (function (BABYLON) {
  44936. /**
  44937. * The Physically based material of BJS.
  44938. *
  44939. * This offers the main features of a standard PBR material.
  44940. * For more information, please refer to the documentation :
  44941. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44942. */
  44943. var PBRMaterial = /** @class */ (function (_super) {
  44944. __extends(PBRMaterial, _super);
  44945. /**
  44946. * Instantiates a new PBRMaterial instance.
  44947. *
  44948. * @param name The material name
  44949. * @param scene The scene the material will be use in.
  44950. */
  44951. function PBRMaterial(name, scene) {
  44952. var _this = _super.call(this, name, scene) || this;
  44953. /**
  44954. * Intensity of the direct lights e.g. the four lights available in your scene.
  44955. * This impacts both the direct diffuse and specular highlights.
  44956. */
  44957. _this.directIntensity = 1.0;
  44958. /**
  44959. * Intensity of the emissive part of the material.
  44960. * This helps controlling the emissive effect without modifying the emissive color.
  44961. */
  44962. _this.emissiveIntensity = 1.0;
  44963. /**
  44964. * Intensity of the environment e.g. how much the environment will light the object
  44965. * either through harmonics for rough material or through the refelction for shiny ones.
  44966. */
  44967. _this.environmentIntensity = 1.0;
  44968. /**
  44969. * This is a special control allowing the reduction of the specular highlights coming from the
  44970. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44971. */
  44972. _this.specularIntensity = 1.0;
  44973. /**
  44974. * Debug Control allowing disabling the bump map on this material.
  44975. */
  44976. _this.disableBumpMap = false;
  44977. /**
  44978. * AKA Occlusion Texture Intensity in other nomenclature.
  44979. */
  44980. _this.ambientTextureStrength = 1.0;
  44981. /**
  44982. * The color of a material in ambient lighting.
  44983. */
  44984. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44985. /**
  44986. * AKA Diffuse Color in other nomenclature.
  44987. */
  44988. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44989. /**
  44990. * AKA Specular Color in other nomenclature.
  44991. */
  44992. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44993. /**
  44994. * The color reflected from the material.
  44995. */
  44996. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44997. /**
  44998. * The color emitted from the material.
  44999. */
  45000. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45001. /**
  45002. * AKA Glossiness in other nomenclature.
  45003. */
  45004. _this.microSurface = 1.0;
  45005. /**
  45006. * source material index of refraction (IOR)' / 'destination material IOR.
  45007. */
  45008. _this.indexOfRefraction = 0.66;
  45009. /**
  45010. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45011. */
  45012. _this.invertRefractionY = false;
  45013. /**
  45014. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45015. * Materials half opaque for instance using refraction could benefit from this control.
  45016. */
  45017. _this.linkRefractionWithTransparency = false;
  45018. _this.useLightmapAsShadowmap = false;
  45019. /**
  45020. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45021. */
  45022. _this.useAlphaFromAlbedoTexture = false;
  45023. /**
  45024. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45025. */
  45026. _this.forceAlphaTest = false;
  45027. /**
  45028. * Defines the alpha limits in alpha test mode.
  45029. */
  45030. _this.alphaCutOff = 0.4;
  45031. /**
  45032. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45033. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45034. */
  45035. _this.useSpecularOverAlpha = true;
  45036. /**
  45037. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45038. */
  45039. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45040. /**
  45041. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45042. */
  45043. _this.useRoughnessFromMetallicTextureAlpha = true;
  45044. /**
  45045. * Specifies if the metallic texture contains the roughness information in its green channel.
  45046. */
  45047. _this.useRoughnessFromMetallicTextureGreen = false;
  45048. /**
  45049. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45050. */
  45051. _this.useMetallnessFromMetallicTextureBlue = false;
  45052. /**
  45053. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45054. */
  45055. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45056. /**
  45057. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45058. */
  45059. _this.useAmbientInGrayScale = false;
  45060. /**
  45061. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45062. * The material will try to infer what glossiness each pixel should be.
  45063. */
  45064. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45065. /**
  45066. * BJS is using an harcoded light falloff based on a manually sets up range.
  45067. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45068. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45069. */
  45070. _this.usePhysicalLightFalloff = true;
  45071. /**
  45072. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45073. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45074. */
  45075. _this.useRadianceOverAlpha = true;
  45076. /**
  45077. * Allows using an object space normal map (instead of tangent space).
  45078. */
  45079. _this.useObjectSpaceNormalMap = false;
  45080. /**
  45081. * Allows using the bump map in parallax mode.
  45082. */
  45083. _this.useParallax = false;
  45084. /**
  45085. * Allows using the bump map in parallax occlusion mode.
  45086. */
  45087. _this.useParallaxOcclusion = false;
  45088. /**
  45089. * Controls the scale bias of the parallax mode.
  45090. */
  45091. _this.parallaxScaleBias = 0.05;
  45092. /**
  45093. * If sets to true, disables all the lights affecting the material.
  45094. */
  45095. _this.disableLighting = false;
  45096. /**
  45097. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45098. */
  45099. _this.forceIrradianceInFragment = false;
  45100. /**
  45101. * Number of Simultaneous lights allowed on the material.
  45102. */
  45103. _this.maxSimultaneousLights = 4;
  45104. /**
  45105. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45106. */
  45107. _this.invertNormalMapX = false;
  45108. /**
  45109. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45110. */
  45111. _this.invertNormalMapY = false;
  45112. /**
  45113. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45114. */
  45115. _this.twoSidedLighting = false;
  45116. /**
  45117. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45118. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45119. */
  45120. _this.useAlphaFresnel = false;
  45121. /**
  45122. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45123. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45124. */
  45125. _this.useLinearAlphaFresnel = false;
  45126. /**
  45127. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45128. * And/Or occlude the blended part.
  45129. */
  45130. _this.environmentBRDFTexture = null;
  45131. /**
  45132. * Force normal to face away from face.
  45133. */
  45134. _this.forceNormalForward = false;
  45135. /**
  45136. * Enables specular anti aliasing in the PBR shader.
  45137. * It will both interacts on the Geometry for analytical and IBL lighting.
  45138. * It also prefilter the roughness map based on the bump values.
  45139. */
  45140. _this.enableSpecularAntiAliasing = false;
  45141. /**
  45142. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45143. * makes the reflect vector face the model (under horizon).
  45144. */
  45145. _this.useHorizonOcclusion = true;
  45146. /**
  45147. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45148. * too much the area relying on ambient texture to define their ambient occlusion.
  45149. */
  45150. _this.useRadianceOcclusion = true;
  45151. /**
  45152. * If set to true, no lighting calculations will be applied.
  45153. */
  45154. _this.unlit = false;
  45155. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45156. return _this;
  45157. }
  45158. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45159. /**
  45160. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45161. */
  45162. get: function () {
  45163. return this._PBRMATERIAL_OPAQUE;
  45164. },
  45165. enumerable: true,
  45166. configurable: true
  45167. });
  45168. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45169. /**
  45170. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45171. */
  45172. get: function () {
  45173. return this._PBRMATERIAL_ALPHATEST;
  45174. },
  45175. enumerable: true,
  45176. configurable: true
  45177. });
  45178. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45179. /**
  45180. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45181. */
  45182. get: function () {
  45183. return this._PBRMATERIAL_ALPHABLEND;
  45184. },
  45185. enumerable: true,
  45186. configurable: true
  45187. });
  45188. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45189. /**
  45190. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45191. * They are also discarded below the alpha cutoff threshold to improve performances.
  45192. */
  45193. get: function () {
  45194. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45195. },
  45196. enumerable: true,
  45197. configurable: true
  45198. });
  45199. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45200. /**
  45201. * Gets the image processing configuration used either in this material.
  45202. */
  45203. get: function () {
  45204. return this._imageProcessingConfiguration;
  45205. },
  45206. /**
  45207. * Sets the Default image processing configuration used either in the this material.
  45208. *
  45209. * If sets to null, the scene one is in use.
  45210. */
  45211. set: function (value) {
  45212. this._attachImageProcessingConfiguration(value);
  45213. // Ensure the effect will be rebuilt.
  45214. this._markAllSubMeshesAsTexturesDirty();
  45215. },
  45216. enumerable: true,
  45217. configurable: true
  45218. });
  45219. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45220. /**
  45221. * Gets wether the color curves effect is enabled.
  45222. */
  45223. get: function () {
  45224. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45225. },
  45226. /**
  45227. * Sets wether the color curves effect is enabled.
  45228. */
  45229. set: function (value) {
  45230. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45231. },
  45232. enumerable: true,
  45233. configurable: true
  45234. });
  45235. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45236. /**
  45237. * Gets wether the color grading effect is enabled.
  45238. */
  45239. get: function () {
  45240. return this.imageProcessingConfiguration.colorGradingEnabled;
  45241. },
  45242. /**
  45243. * Gets wether the color grading effect is enabled.
  45244. */
  45245. set: function (value) {
  45246. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45247. },
  45248. enumerable: true,
  45249. configurable: true
  45250. });
  45251. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45252. /**
  45253. * Gets wether tonemapping is enabled or not.
  45254. */
  45255. get: function () {
  45256. return this._imageProcessingConfiguration.toneMappingEnabled;
  45257. },
  45258. /**
  45259. * Sets wether tonemapping is enabled or not
  45260. */
  45261. set: function (value) {
  45262. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45263. },
  45264. enumerable: true,
  45265. configurable: true
  45266. });
  45267. ;
  45268. ;
  45269. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45270. /**
  45271. * The camera exposure used on this material.
  45272. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45273. * This corresponds to a photographic exposure.
  45274. */
  45275. get: function () {
  45276. return this._imageProcessingConfiguration.exposure;
  45277. },
  45278. /**
  45279. * The camera exposure used on this material.
  45280. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45281. * This corresponds to a photographic exposure.
  45282. */
  45283. set: function (value) {
  45284. this._imageProcessingConfiguration.exposure = value;
  45285. },
  45286. enumerable: true,
  45287. configurable: true
  45288. });
  45289. ;
  45290. ;
  45291. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45292. /**
  45293. * Gets The camera contrast used on this material.
  45294. */
  45295. get: function () {
  45296. return this._imageProcessingConfiguration.contrast;
  45297. },
  45298. /**
  45299. * Sets The camera contrast used on this material.
  45300. */
  45301. set: function (value) {
  45302. this._imageProcessingConfiguration.contrast = value;
  45303. },
  45304. enumerable: true,
  45305. configurable: true
  45306. });
  45307. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45308. /**
  45309. * Gets the Color Grading 2D Lookup Texture.
  45310. */
  45311. get: function () {
  45312. return this._imageProcessingConfiguration.colorGradingTexture;
  45313. },
  45314. /**
  45315. * Sets the Color Grading 2D Lookup Texture.
  45316. */
  45317. set: function (value) {
  45318. this._imageProcessingConfiguration.colorGradingTexture = value;
  45319. },
  45320. enumerable: true,
  45321. configurable: true
  45322. });
  45323. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45324. /**
  45325. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45326. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45327. * 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;
  45328. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45329. */
  45330. get: function () {
  45331. return this._imageProcessingConfiguration.colorCurves;
  45332. },
  45333. /**
  45334. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45335. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45336. * 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;
  45337. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45338. */
  45339. set: function (value) {
  45340. this._imageProcessingConfiguration.colorCurves = value;
  45341. },
  45342. enumerable: true,
  45343. configurable: true
  45344. });
  45345. /**
  45346. * Returns the name of this material class.
  45347. */
  45348. PBRMaterial.prototype.getClassName = function () {
  45349. return "PBRMaterial";
  45350. };
  45351. /**
  45352. * Returns an array of the actively used textures.
  45353. * @returns - Array of BaseTextures
  45354. */
  45355. PBRMaterial.prototype.getActiveTextures = function () {
  45356. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45357. if (this._albedoTexture) {
  45358. activeTextures.push(this._albedoTexture);
  45359. }
  45360. if (this._ambientTexture) {
  45361. activeTextures.push(this._ambientTexture);
  45362. }
  45363. if (this._opacityTexture) {
  45364. activeTextures.push(this._opacityTexture);
  45365. }
  45366. if (this._reflectionTexture) {
  45367. activeTextures.push(this._reflectionTexture);
  45368. }
  45369. if (this._emissiveTexture) {
  45370. activeTextures.push(this._emissiveTexture);
  45371. }
  45372. if (this._reflectivityTexture) {
  45373. activeTextures.push(this._reflectivityTexture);
  45374. }
  45375. if (this._metallicTexture) {
  45376. activeTextures.push(this._metallicTexture);
  45377. }
  45378. if (this._microSurfaceTexture) {
  45379. activeTextures.push(this._microSurfaceTexture);
  45380. }
  45381. if (this._bumpTexture) {
  45382. activeTextures.push(this._bumpTexture);
  45383. }
  45384. if (this._lightmapTexture) {
  45385. activeTextures.push(this._lightmapTexture);
  45386. }
  45387. if (this._refractionTexture) {
  45388. activeTextures.push(this._refractionTexture);
  45389. }
  45390. return activeTextures;
  45391. };
  45392. /**
  45393. * Checks to see if a texture is used in the material.
  45394. * @param texture - Base texture to use.
  45395. * @returns - Boolean specifying if a texture is used in the material.
  45396. */
  45397. PBRMaterial.prototype.hasTexture = function (texture) {
  45398. if (_super.prototype.hasTexture.call(this, texture)) {
  45399. return true;
  45400. }
  45401. if (this._albedoTexture === texture) {
  45402. return true;
  45403. }
  45404. if (this._ambientTexture === texture) {
  45405. return true;
  45406. }
  45407. if (this._opacityTexture === texture) {
  45408. return true;
  45409. }
  45410. if (this._reflectionTexture === texture) {
  45411. return true;
  45412. }
  45413. if (this._reflectivityTexture === texture) {
  45414. return true;
  45415. }
  45416. if (this._metallicTexture === texture) {
  45417. return true;
  45418. }
  45419. if (this._microSurfaceTexture === texture) {
  45420. return true;
  45421. }
  45422. if (this._bumpTexture === texture) {
  45423. return true;
  45424. }
  45425. if (this._lightmapTexture === texture) {
  45426. return true;
  45427. }
  45428. if (this._refractionTexture === texture) {
  45429. return true;
  45430. }
  45431. return false;
  45432. };
  45433. /**
  45434. * Makes a duplicate of the current material.
  45435. * @param name - name to use for the new material.
  45436. */
  45437. PBRMaterial.prototype.clone = function (name) {
  45438. var _this = this;
  45439. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45440. clone.id = name;
  45441. clone.name = name;
  45442. return clone;
  45443. };
  45444. /**
  45445. * Serializes this PBR Material.
  45446. * @returns - An object with the serialized material.
  45447. */
  45448. PBRMaterial.prototype.serialize = function () {
  45449. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45450. serializationObject.customType = "BABYLON.PBRMaterial";
  45451. return serializationObject;
  45452. };
  45453. // Statics
  45454. /**
  45455. * Parses a PBR Material from a serialized object.
  45456. * @param source - Serialized object.
  45457. * @param scene - BJS scene instance.
  45458. * @param rootUrl - url for the scene object
  45459. * @returns - PBRMaterial
  45460. */
  45461. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45462. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45463. };
  45464. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45465. /**
  45466. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45467. */
  45468. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45469. /**
  45470. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45471. */
  45472. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45473. /**
  45474. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45475. * They are also discarded below the alpha cutoff threshold to improve performances.
  45476. */
  45477. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45478. __decorate([
  45479. BABYLON.serialize(),
  45480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45481. ], PBRMaterial.prototype, "directIntensity", void 0);
  45482. __decorate([
  45483. BABYLON.serialize(),
  45484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45485. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45486. __decorate([
  45487. BABYLON.serialize(),
  45488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45489. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45490. __decorate([
  45491. BABYLON.serialize(),
  45492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45493. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45494. __decorate([
  45495. BABYLON.serialize(),
  45496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45497. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45498. __decorate([
  45499. BABYLON.serializeAsTexture(),
  45500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45501. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45502. __decorate([
  45503. BABYLON.serializeAsTexture(),
  45504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45505. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45506. __decorate([
  45507. BABYLON.serialize(),
  45508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45509. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45510. __decorate([
  45511. BABYLON.serializeAsTexture(),
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45513. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45514. __decorate([
  45515. BABYLON.serializeAsTexture(),
  45516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45517. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45518. __decorate([
  45519. BABYLON.serializeAsTexture(),
  45520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45521. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45522. __decorate([
  45523. BABYLON.serializeAsTexture(),
  45524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45525. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45526. __decorate([
  45527. BABYLON.serializeAsTexture(),
  45528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45529. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45530. __decorate([
  45531. BABYLON.serialize(),
  45532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45533. ], PBRMaterial.prototype, "metallic", void 0);
  45534. __decorate([
  45535. BABYLON.serialize(),
  45536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45537. ], PBRMaterial.prototype, "roughness", void 0);
  45538. __decorate([
  45539. BABYLON.serializeAsTexture(),
  45540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45541. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45542. __decorate([
  45543. BABYLON.serializeAsTexture(),
  45544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45545. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45546. __decorate([
  45547. BABYLON.serializeAsTexture(),
  45548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45549. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45550. __decorate([
  45551. BABYLON.serializeAsTexture(),
  45552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45553. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45554. __decorate([
  45555. BABYLON.serializeAsColor3("ambient"),
  45556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45557. ], PBRMaterial.prototype, "ambientColor", void 0);
  45558. __decorate([
  45559. BABYLON.serializeAsColor3("albedo"),
  45560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45561. ], PBRMaterial.prototype, "albedoColor", void 0);
  45562. __decorate([
  45563. BABYLON.serializeAsColor3("reflectivity"),
  45564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45565. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45566. __decorate([
  45567. BABYLON.serializeAsColor3("reflection"),
  45568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45569. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45570. __decorate([
  45571. BABYLON.serializeAsColor3("emissive"),
  45572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45573. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45574. __decorate([
  45575. BABYLON.serialize(),
  45576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45577. ], PBRMaterial.prototype, "microSurface", void 0);
  45578. __decorate([
  45579. BABYLON.serialize(),
  45580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45581. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45582. __decorate([
  45583. BABYLON.serialize(),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45585. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45586. __decorate([
  45587. BABYLON.serialize(),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45589. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45593. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45594. __decorate([
  45595. BABYLON.serialize(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45597. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45598. __decorate([
  45599. BABYLON.serialize(),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45601. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45602. __decorate([
  45603. BABYLON.serialize(),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45605. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45609. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45610. __decorate([
  45611. BABYLON.serialize(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45613. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45614. __decorate([
  45615. BABYLON.serialize(),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45617. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45618. __decorate([
  45619. BABYLON.serialize(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45621. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45625. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45626. __decorate([
  45627. BABYLON.serialize(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45629. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45630. __decorate([
  45631. BABYLON.serialize(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45633. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45637. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45638. __decorate([
  45639. BABYLON.serialize(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45641. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45642. __decorate([
  45643. BABYLON.serialize(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45645. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45646. __decorate([
  45647. BABYLON.serialize(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45649. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMaterial.prototype, "useParallax", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45657. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45658. __decorate([
  45659. BABYLON.serialize(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45661. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45662. __decorate([
  45663. BABYLON.serialize(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45665. ], PBRMaterial.prototype, "disableLighting", void 0);
  45666. __decorate([
  45667. BABYLON.serialize(),
  45668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45669. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45670. __decorate([
  45671. BABYLON.serialize(),
  45672. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45673. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45674. __decorate([
  45675. BABYLON.serialize(),
  45676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45677. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45678. __decorate([
  45679. BABYLON.serialize(),
  45680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45681. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45682. __decorate([
  45683. BABYLON.serialize(),
  45684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45685. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45686. __decorate([
  45687. BABYLON.serialize(),
  45688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45689. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45690. __decorate([
  45691. BABYLON.serialize(),
  45692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45693. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45694. __decorate([
  45695. BABYLON.serializeAsTexture(),
  45696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45697. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45698. __decorate([
  45699. BABYLON.serialize(),
  45700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45701. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45702. __decorate([
  45703. BABYLON.serialize(),
  45704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45705. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45706. __decorate([
  45707. BABYLON.serialize(),
  45708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45709. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45710. __decorate([
  45711. BABYLON.serialize(),
  45712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45713. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45714. __decorate([
  45715. BABYLON.serialize(),
  45716. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45717. ], PBRMaterial.prototype, "unlit", void 0);
  45718. return PBRMaterial;
  45719. }(BABYLON.PBRBaseMaterial));
  45720. BABYLON.PBRMaterial = PBRMaterial;
  45721. })(BABYLON || (BABYLON = {}));
  45722. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45723. var BABYLON;
  45724. (function (BABYLON) {
  45725. /**
  45726. * The PBR material of BJS following the metal roughness convention.
  45727. *
  45728. * This fits to the PBR convention in the GLTF definition:
  45729. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45730. */
  45731. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45732. __extends(PBRMetallicRoughnessMaterial, _super);
  45733. /**
  45734. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45735. *
  45736. * @param name The material name
  45737. * @param scene The scene the material will be use in.
  45738. */
  45739. function PBRMetallicRoughnessMaterial(name, scene) {
  45740. var _this = _super.call(this, name, scene) || this;
  45741. _this._useRoughnessFromMetallicTextureAlpha = false;
  45742. _this._useRoughnessFromMetallicTextureGreen = true;
  45743. _this._useMetallnessFromMetallicTextureBlue = true;
  45744. _this.metallic = 1.0;
  45745. _this.roughness = 1.0;
  45746. return _this;
  45747. }
  45748. /**
  45749. * Return the currrent class name of the material.
  45750. */
  45751. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45752. return "PBRMetallicRoughnessMaterial";
  45753. };
  45754. /**
  45755. * Return the active textures of the material.
  45756. */
  45757. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45758. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45759. if (this.baseTexture) {
  45760. activeTextures.push(this.baseTexture);
  45761. }
  45762. if (this.metallicRoughnessTexture) {
  45763. activeTextures.push(this.metallicRoughnessTexture);
  45764. }
  45765. return activeTextures;
  45766. };
  45767. /**
  45768. * Checks to see if a texture is used in the material.
  45769. * @param texture - Base texture to use.
  45770. * @returns - Boolean specifying if a texture is used in the material.
  45771. */
  45772. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45773. if (_super.prototype.hasTexture.call(this, texture)) {
  45774. return true;
  45775. }
  45776. if (this.baseTexture === texture) {
  45777. return true;
  45778. }
  45779. if (this.metallicRoughnessTexture === texture) {
  45780. return true;
  45781. }
  45782. return false;
  45783. };
  45784. /**
  45785. * Makes a duplicate of the current material.
  45786. * @param name - name to use for the new material.
  45787. */
  45788. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45789. var _this = this;
  45790. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45791. clone.id = name;
  45792. clone.name = name;
  45793. return clone;
  45794. };
  45795. /**
  45796. * Serialize the material to a parsable JSON object.
  45797. */
  45798. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45799. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45800. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45801. return serializationObject;
  45802. };
  45803. /**
  45804. * Parses a JSON object correponding to the serialize function.
  45805. */
  45806. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45807. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45808. };
  45809. __decorate([
  45810. BABYLON.serializeAsColor3(),
  45811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45812. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45813. __decorate([
  45814. BABYLON.serializeAsTexture(),
  45815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45816. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45817. __decorate([
  45818. BABYLON.serialize(),
  45819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45820. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45821. __decorate([
  45822. BABYLON.serialize(),
  45823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45824. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45825. __decorate([
  45826. BABYLON.serializeAsTexture(),
  45827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45828. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45829. return PBRMetallicRoughnessMaterial;
  45830. }(BABYLON.PBRBaseSimpleMaterial));
  45831. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45832. })(BABYLON || (BABYLON = {}));
  45833. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45834. var BABYLON;
  45835. (function (BABYLON) {
  45836. /**
  45837. * The PBR material of BJS following the specular glossiness convention.
  45838. *
  45839. * This fits to the PBR convention in the GLTF definition:
  45840. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45841. */
  45842. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45843. __extends(PBRSpecularGlossinessMaterial, _super);
  45844. /**
  45845. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45846. *
  45847. * @param name The material name
  45848. * @param scene The scene the material will be use in.
  45849. */
  45850. function PBRSpecularGlossinessMaterial(name, scene) {
  45851. var _this = _super.call(this, name, scene) || this;
  45852. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45853. return _this;
  45854. }
  45855. /**
  45856. * Return the currrent class name of the material.
  45857. */
  45858. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45859. return "PBRSpecularGlossinessMaterial";
  45860. };
  45861. /**
  45862. * Return the active textures of the material.
  45863. */
  45864. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45865. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45866. if (this.diffuseTexture) {
  45867. activeTextures.push(this.diffuseTexture);
  45868. }
  45869. if (this.specularGlossinessTexture) {
  45870. activeTextures.push(this.specularGlossinessTexture);
  45871. }
  45872. return activeTextures;
  45873. };
  45874. /**
  45875. * Checks to see if a texture is used in the material.
  45876. * @param texture - Base texture to use.
  45877. * @returns - Boolean specifying if a texture is used in the material.
  45878. */
  45879. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45880. if (_super.prototype.hasTexture.call(this, texture)) {
  45881. return true;
  45882. }
  45883. if (this.diffuseTexture === texture) {
  45884. return true;
  45885. }
  45886. if (this.specularGlossinessTexture === texture) {
  45887. return true;
  45888. }
  45889. return false;
  45890. };
  45891. /**
  45892. * Makes a duplicate of the current material.
  45893. * @param name - name to use for the new material.
  45894. */
  45895. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45896. var _this = this;
  45897. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45898. clone.id = name;
  45899. clone.name = name;
  45900. return clone;
  45901. };
  45902. /**
  45903. * Serialize the material to a parsable JSON object.
  45904. */
  45905. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45906. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45907. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45908. return serializationObject;
  45909. };
  45910. /**
  45911. * Parses a JSON object correponding to the serialize function.
  45912. */
  45913. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45914. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45915. };
  45916. __decorate([
  45917. BABYLON.serializeAsColor3("diffuse"),
  45918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45919. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45920. __decorate([
  45921. BABYLON.serializeAsTexture(),
  45922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45923. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45924. __decorate([
  45925. BABYLON.serializeAsColor3("specular"),
  45926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45927. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45928. __decorate([
  45929. BABYLON.serialize(),
  45930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45931. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45932. __decorate([
  45933. BABYLON.serializeAsTexture(),
  45934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45935. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45936. return PBRSpecularGlossinessMaterial;
  45937. }(BABYLON.PBRBaseSimpleMaterial));
  45938. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45939. })(BABYLON || (BABYLON = {}));
  45940. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45941. var BABYLON;
  45942. (function (BABYLON) {
  45943. BABYLON.CameraInputTypes = {};
  45944. var CameraInputsManager = /** @class */ (function () {
  45945. function CameraInputsManager(camera) {
  45946. this.attached = {};
  45947. this.camera = camera;
  45948. this.checkInputs = function () { };
  45949. }
  45950. /**
  45951. * Add an input method to a camera.
  45952. * builtin inputs example: camera.inputs.addGamepad();
  45953. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45954. * @param input camera input method
  45955. */
  45956. CameraInputsManager.prototype.add = function (input) {
  45957. var type = input.getSimpleName();
  45958. if (this.attached[type]) {
  45959. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45960. return;
  45961. }
  45962. this.attached[type] = input;
  45963. input.camera = this.camera;
  45964. //for checkInputs, we are dynamically creating a function
  45965. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45966. if (input.checkInputs) {
  45967. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45968. }
  45969. if (this.attachedElement) {
  45970. input.attachControl(this.attachedElement);
  45971. }
  45972. };
  45973. /**
  45974. * Remove a specific input method from a camera
  45975. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45976. * @param inputToRemove camera input method
  45977. */
  45978. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45979. for (var cam in this.attached) {
  45980. var input = this.attached[cam];
  45981. if (input === inputToRemove) {
  45982. input.detachControl(this.attachedElement);
  45983. input.camera = null;
  45984. delete this.attached[cam];
  45985. this.rebuildInputCheck();
  45986. }
  45987. }
  45988. };
  45989. CameraInputsManager.prototype.removeByType = function (inputType) {
  45990. for (var cam in this.attached) {
  45991. var input = this.attached[cam];
  45992. if (input.getClassName() === inputType) {
  45993. input.detachControl(this.attachedElement);
  45994. input.camera = null;
  45995. delete this.attached[cam];
  45996. this.rebuildInputCheck();
  45997. }
  45998. }
  45999. };
  46000. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46001. var current = this.checkInputs;
  46002. return function () {
  46003. current();
  46004. fn();
  46005. };
  46006. };
  46007. CameraInputsManager.prototype.attachInput = function (input) {
  46008. if (this.attachedElement) {
  46009. input.attachControl(this.attachedElement, this.noPreventDefault);
  46010. }
  46011. };
  46012. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46013. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46014. if (this.attachedElement) {
  46015. return;
  46016. }
  46017. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46018. this.attachedElement = element;
  46019. this.noPreventDefault = noPreventDefault;
  46020. for (var cam in this.attached) {
  46021. this.attached[cam].attachControl(element, noPreventDefault);
  46022. }
  46023. };
  46024. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46025. if (disconnect === void 0) { disconnect = false; }
  46026. if (this.attachedElement !== element) {
  46027. return;
  46028. }
  46029. for (var cam in this.attached) {
  46030. this.attached[cam].detachControl(element);
  46031. if (disconnect) {
  46032. this.attached[cam].camera = null;
  46033. }
  46034. }
  46035. this.attachedElement = null;
  46036. };
  46037. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46038. this.checkInputs = function () { };
  46039. for (var cam in this.attached) {
  46040. var input = this.attached[cam];
  46041. if (input.checkInputs) {
  46042. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46043. }
  46044. }
  46045. };
  46046. /**
  46047. * Remove all attached input methods from a camera
  46048. */
  46049. CameraInputsManager.prototype.clear = function () {
  46050. if (this.attachedElement) {
  46051. this.detachElement(this.attachedElement, true);
  46052. }
  46053. this.attached = {};
  46054. this.attachedElement = null;
  46055. this.checkInputs = function () { };
  46056. };
  46057. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46058. var inputs = {};
  46059. for (var cam in this.attached) {
  46060. var input = this.attached[cam];
  46061. var res = BABYLON.SerializationHelper.Serialize(input);
  46062. inputs[input.getClassName()] = res;
  46063. }
  46064. serializedCamera.inputsmgr = inputs;
  46065. };
  46066. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46067. var parsedInputs = parsedCamera.inputsmgr;
  46068. if (parsedInputs) {
  46069. this.clear();
  46070. for (var n in parsedInputs) {
  46071. var construct = BABYLON.CameraInputTypes[n];
  46072. if (construct) {
  46073. var parsedinput = parsedInputs[n];
  46074. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46075. this.add(input);
  46076. }
  46077. }
  46078. }
  46079. else {
  46080. //2016-03-08 this part is for managing backward compatibility
  46081. for (var n in this.attached) {
  46082. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46083. if (construct) {
  46084. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46085. this.remove(this.attached[n]);
  46086. this.add(input);
  46087. }
  46088. }
  46089. }
  46090. };
  46091. return CameraInputsManager;
  46092. }());
  46093. BABYLON.CameraInputsManager = CameraInputsManager;
  46094. })(BABYLON || (BABYLON = {}));
  46095. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46096. var BABYLON;
  46097. (function (BABYLON) {
  46098. var TargetCamera = /** @class */ (function (_super) {
  46099. __extends(TargetCamera, _super);
  46100. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46101. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46102. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46103. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46104. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46105. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46106. _this.speed = 2.0;
  46107. _this.noRotationConstraint = false;
  46108. _this.lockedTarget = null;
  46109. _this._currentTarget = BABYLON.Vector3.Zero();
  46110. _this._viewMatrix = BABYLON.Matrix.Zero();
  46111. _this._camMatrix = BABYLON.Matrix.Zero();
  46112. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46113. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46114. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46115. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46116. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46117. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46118. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46119. return _this;
  46120. }
  46121. TargetCamera.prototype.getFrontPosition = function (distance) {
  46122. this.getWorldMatrix();
  46123. var direction = this.getTarget().subtract(this.position);
  46124. direction.normalize();
  46125. direction.scaleInPlace(distance);
  46126. return this.globalPosition.add(direction);
  46127. };
  46128. TargetCamera.prototype._getLockedTargetPosition = function () {
  46129. if (!this.lockedTarget) {
  46130. return null;
  46131. }
  46132. if (this.lockedTarget.absolutePosition) {
  46133. this.lockedTarget.computeWorldMatrix();
  46134. }
  46135. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46136. };
  46137. TargetCamera.prototype.storeState = function () {
  46138. this._storedPosition = this.position.clone();
  46139. this._storedRotation = this.rotation.clone();
  46140. if (this.rotationQuaternion) {
  46141. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46142. }
  46143. return _super.prototype.storeState.call(this);
  46144. };
  46145. /**
  46146. * Restored camera state. You must call storeState() first
  46147. */
  46148. TargetCamera.prototype._restoreStateValues = function () {
  46149. if (!_super.prototype._restoreStateValues.call(this)) {
  46150. return false;
  46151. }
  46152. this.position = this._storedPosition.clone();
  46153. this.rotation = this._storedRotation.clone();
  46154. if (this.rotationQuaternion) {
  46155. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46156. }
  46157. this.cameraDirection.copyFromFloats(0, 0, 0);
  46158. this.cameraRotation.copyFromFloats(0, 0);
  46159. return true;
  46160. };
  46161. // Cache
  46162. TargetCamera.prototype._initCache = function () {
  46163. _super.prototype._initCache.call(this);
  46164. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46165. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46166. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46167. };
  46168. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46169. if (!ignoreParentClass) {
  46170. _super.prototype._updateCache.call(this);
  46171. }
  46172. var lockedTargetPosition = this._getLockedTargetPosition();
  46173. if (!lockedTargetPosition) {
  46174. this._cache.lockedTarget = null;
  46175. }
  46176. else {
  46177. if (!this._cache.lockedTarget) {
  46178. this._cache.lockedTarget = lockedTargetPosition.clone();
  46179. }
  46180. else {
  46181. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46182. }
  46183. }
  46184. this._cache.rotation.copyFrom(this.rotation);
  46185. if (this.rotationQuaternion)
  46186. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46187. };
  46188. // Synchronized
  46189. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46190. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46191. return false;
  46192. }
  46193. var lockedTargetPosition = this._getLockedTargetPosition();
  46194. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46195. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46196. };
  46197. // Methods
  46198. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46199. var engine = this.getEngine();
  46200. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46201. };
  46202. // Target
  46203. TargetCamera.prototype.setTarget = function (target) {
  46204. this.upVector.normalize();
  46205. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46206. this._camMatrix.invert();
  46207. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46208. var vDir = target.subtract(this.position);
  46209. if (vDir.x >= 0.0) {
  46210. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46211. }
  46212. else {
  46213. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46214. }
  46215. this.rotation.z = 0;
  46216. if (isNaN(this.rotation.x)) {
  46217. this.rotation.x = 0;
  46218. }
  46219. if (isNaN(this.rotation.y)) {
  46220. this.rotation.y = 0;
  46221. }
  46222. if (isNaN(this.rotation.z)) {
  46223. this.rotation.z = 0;
  46224. }
  46225. if (this.rotationQuaternion) {
  46226. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46227. }
  46228. };
  46229. /**
  46230. * Return the current target position of the camera. This value is expressed in local space.
  46231. */
  46232. TargetCamera.prototype.getTarget = function () {
  46233. return this._currentTarget;
  46234. };
  46235. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46236. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46237. };
  46238. TargetCamera.prototype._updatePosition = function () {
  46239. if (this.parent) {
  46240. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46241. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46242. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46243. return;
  46244. }
  46245. this.position.addInPlace(this.cameraDirection);
  46246. };
  46247. TargetCamera.prototype._checkInputs = function () {
  46248. var needToMove = this._decideIfNeedsToMove();
  46249. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46250. // Move
  46251. if (needToMove) {
  46252. this._updatePosition();
  46253. }
  46254. // Rotate
  46255. if (needToRotate) {
  46256. this.rotation.x += this.cameraRotation.x;
  46257. this.rotation.y += this.cameraRotation.y;
  46258. //rotate, if quaternion is set and rotation was used
  46259. if (this.rotationQuaternion) {
  46260. var len = this.rotation.lengthSquared();
  46261. if (len) {
  46262. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46263. }
  46264. }
  46265. if (!this.noRotationConstraint) {
  46266. var limit = (Math.PI / 2) * 0.95;
  46267. if (this.rotation.x > limit)
  46268. this.rotation.x = limit;
  46269. if (this.rotation.x < -limit)
  46270. this.rotation.x = -limit;
  46271. }
  46272. }
  46273. // Inertia
  46274. if (needToMove) {
  46275. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46276. this.cameraDirection.x = 0;
  46277. }
  46278. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46279. this.cameraDirection.y = 0;
  46280. }
  46281. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46282. this.cameraDirection.z = 0;
  46283. }
  46284. this.cameraDirection.scaleInPlace(this.inertia);
  46285. }
  46286. if (needToRotate) {
  46287. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46288. this.cameraRotation.x = 0;
  46289. }
  46290. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46291. this.cameraRotation.y = 0;
  46292. }
  46293. this.cameraRotation.scaleInPlace(this.inertia);
  46294. }
  46295. _super.prototype._checkInputs.call(this);
  46296. };
  46297. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46298. if (this.rotationQuaternion) {
  46299. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46300. }
  46301. else {
  46302. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46303. }
  46304. //update the up vector!
  46305. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46306. };
  46307. TargetCamera.prototype._getViewMatrix = function () {
  46308. if (this.lockedTarget) {
  46309. this.setTarget(this._getLockedTargetPosition());
  46310. }
  46311. // Compute
  46312. this._updateCameraRotationMatrix();
  46313. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46314. // Computing target and final matrix
  46315. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46316. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46317. return this._viewMatrix;
  46318. };
  46319. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46320. if (this.parent) {
  46321. var parentWorldMatrix = this.parent.getWorldMatrix();
  46322. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46323. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46324. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46325. this._markSyncedWithParent();
  46326. }
  46327. else {
  46328. this._globalPosition.copyFrom(this.position);
  46329. this._globalCurrentTarget.copyFrom(target);
  46330. this._globalCurrentUpVector.copyFrom(up);
  46331. }
  46332. if (this.getScene().useRightHandedSystem) {
  46333. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46334. }
  46335. else {
  46336. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46337. }
  46338. };
  46339. /**
  46340. * @override
  46341. * Override Camera.createRigCamera
  46342. */
  46343. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46344. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46345. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46346. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46347. if (!this.rotationQuaternion) {
  46348. this.rotationQuaternion = new BABYLON.Quaternion();
  46349. }
  46350. rigCamera._cameraRigParams = {};
  46351. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46352. }
  46353. return rigCamera;
  46354. }
  46355. return null;
  46356. };
  46357. /**
  46358. * @override
  46359. * Override Camera._updateRigCameras
  46360. */
  46361. TargetCamera.prototype._updateRigCameras = function () {
  46362. var camLeft = this._rigCameras[0];
  46363. var camRight = this._rigCameras[1];
  46364. switch (this.cameraRigMode) {
  46365. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46366. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46367. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46368. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46369. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46370. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46371. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46372. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46373. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46374. camLeft.setTarget(this.getTarget());
  46375. camRight.setTarget(this.getTarget());
  46376. break;
  46377. case BABYLON.Camera.RIG_MODE_VR:
  46378. if (camLeft.rotationQuaternion) {
  46379. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46380. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46381. }
  46382. else {
  46383. camLeft.rotation.copyFrom(this.rotation);
  46384. camRight.rotation.copyFrom(this.rotation);
  46385. }
  46386. camLeft.position.copyFrom(this.position);
  46387. camRight.position.copyFrom(this.position);
  46388. break;
  46389. }
  46390. _super.prototype._updateRigCameras.call(this);
  46391. };
  46392. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46393. if (!this._rigCamTransformMatrix) {
  46394. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46395. }
  46396. var target = this.getTarget();
  46397. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46398. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46399. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46400. };
  46401. TargetCamera.prototype.getClassName = function () {
  46402. return "TargetCamera";
  46403. };
  46404. __decorate([
  46405. BABYLON.serializeAsVector3()
  46406. ], TargetCamera.prototype, "rotation", void 0);
  46407. __decorate([
  46408. BABYLON.serialize()
  46409. ], TargetCamera.prototype, "speed", void 0);
  46410. __decorate([
  46411. BABYLON.serializeAsMeshReference("lockedTargetId")
  46412. ], TargetCamera.prototype, "lockedTarget", void 0);
  46413. return TargetCamera;
  46414. }(BABYLON.Camera));
  46415. BABYLON.TargetCamera = TargetCamera;
  46416. })(BABYLON || (BABYLON = {}));
  46417. //# sourceMappingURL=babylon.targetCamera.js.map
  46418. var BABYLON;
  46419. (function (BABYLON) {
  46420. var FreeCameraMouseInput = /** @class */ (function () {
  46421. function FreeCameraMouseInput(touchEnabled) {
  46422. if (touchEnabled === void 0) { touchEnabled = true; }
  46423. this.touchEnabled = touchEnabled;
  46424. this.buttons = [0, 1, 2];
  46425. this.angularSensibility = 2000.0;
  46426. this.previousPosition = null;
  46427. }
  46428. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46429. var _this = this;
  46430. var engine = this.camera.getEngine();
  46431. if (!this._pointerInput) {
  46432. this._pointerInput = function (p, s) {
  46433. var evt = p.event;
  46434. if (engine.isInVRExclusivePointerMode) {
  46435. return;
  46436. }
  46437. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46438. return;
  46439. }
  46440. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46441. return;
  46442. }
  46443. var srcElement = (evt.srcElement || evt.target);
  46444. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46445. try {
  46446. srcElement.setPointerCapture(evt.pointerId);
  46447. }
  46448. catch (e) {
  46449. //Nothing to do with the error. Execution will continue.
  46450. }
  46451. _this.previousPosition = {
  46452. x: evt.clientX,
  46453. y: evt.clientY
  46454. };
  46455. if (!noPreventDefault) {
  46456. evt.preventDefault();
  46457. element.focus();
  46458. }
  46459. }
  46460. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46461. try {
  46462. srcElement.releasePointerCapture(evt.pointerId);
  46463. }
  46464. catch (e) {
  46465. //Nothing to do with the error.
  46466. }
  46467. _this.previousPosition = null;
  46468. if (!noPreventDefault) {
  46469. evt.preventDefault();
  46470. }
  46471. }
  46472. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46473. if (!_this.previousPosition || engine.isPointerLock) {
  46474. return;
  46475. }
  46476. var offsetX = evt.clientX - _this.previousPosition.x;
  46477. if (_this.camera.getScene().useRightHandedSystem)
  46478. offsetX *= -1;
  46479. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46480. offsetX *= -1;
  46481. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46482. var offsetY = evt.clientY - _this.previousPosition.y;
  46483. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46484. _this.previousPosition = {
  46485. x: evt.clientX,
  46486. y: evt.clientY
  46487. };
  46488. if (!noPreventDefault) {
  46489. evt.preventDefault();
  46490. }
  46491. }
  46492. };
  46493. }
  46494. this._onMouseMove = function (evt) {
  46495. if (!engine.isPointerLock) {
  46496. return;
  46497. }
  46498. if (engine.isInVRExclusivePointerMode) {
  46499. return;
  46500. }
  46501. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46502. if (_this.camera.getScene().useRightHandedSystem)
  46503. offsetX *= -1;
  46504. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46505. offsetX *= -1;
  46506. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46507. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46508. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46509. _this.previousPosition = null;
  46510. if (!noPreventDefault) {
  46511. evt.preventDefault();
  46512. }
  46513. };
  46514. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46515. element.addEventListener("mousemove", this._onMouseMove, false);
  46516. };
  46517. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46518. if (this._observer && element) {
  46519. this.camera.getScene().onPointerObservable.remove(this._observer);
  46520. if (this._onMouseMove) {
  46521. element.removeEventListener("mousemove", this._onMouseMove);
  46522. }
  46523. this._observer = null;
  46524. this._onMouseMove = null;
  46525. this.previousPosition = null;
  46526. }
  46527. };
  46528. FreeCameraMouseInput.prototype.getClassName = function () {
  46529. return "FreeCameraMouseInput";
  46530. };
  46531. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46532. return "mouse";
  46533. };
  46534. __decorate([
  46535. BABYLON.serialize()
  46536. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46537. __decorate([
  46538. BABYLON.serialize()
  46539. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46540. return FreeCameraMouseInput;
  46541. }());
  46542. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46543. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46544. })(BABYLON || (BABYLON = {}));
  46545. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46546. var BABYLON;
  46547. (function (BABYLON) {
  46548. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46549. function FreeCameraKeyboardMoveInput() {
  46550. this._keys = new Array();
  46551. this.keysUp = [38];
  46552. this.keysDown = [40];
  46553. this.keysLeft = [37];
  46554. this.keysRight = [39];
  46555. }
  46556. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46557. var _this = this;
  46558. if (this._onCanvasBlurObserver) {
  46559. return;
  46560. }
  46561. this._scene = this.camera.getScene();
  46562. this._engine = this._scene.getEngine();
  46563. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46564. _this._keys = [];
  46565. });
  46566. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46567. var evt = info.event;
  46568. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46569. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46570. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46571. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46572. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46573. var index = _this._keys.indexOf(evt.keyCode);
  46574. if (index === -1) {
  46575. _this._keys.push(evt.keyCode);
  46576. }
  46577. if (!noPreventDefault) {
  46578. evt.preventDefault();
  46579. }
  46580. }
  46581. }
  46582. else {
  46583. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46584. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46585. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46586. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46587. var index = _this._keys.indexOf(evt.keyCode);
  46588. if (index >= 0) {
  46589. _this._keys.splice(index, 1);
  46590. }
  46591. if (!noPreventDefault) {
  46592. evt.preventDefault();
  46593. }
  46594. }
  46595. }
  46596. });
  46597. };
  46598. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46599. if (this._scene) {
  46600. if (this._onKeyboardObserver) {
  46601. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46602. }
  46603. if (this._onCanvasBlurObserver) {
  46604. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46605. }
  46606. this._onKeyboardObserver = null;
  46607. this._onCanvasBlurObserver = null;
  46608. }
  46609. this._keys = [];
  46610. };
  46611. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46612. if (this._onKeyboardObserver) {
  46613. var camera = this.camera;
  46614. // Keyboard
  46615. for (var index = 0; index < this._keys.length; index++) {
  46616. var keyCode = this._keys[index];
  46617. var speed = camera._computeLocalCameraSpeed();
  46618. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46619. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46620. }
  46621. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46622. camera._localDirection.copyFromFloats(0, 0, speed);
  46623. }
  46624. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46625. camera._localDirection.copyFromFloats(speed, 0, 0);
  46626. }
  46627. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46628. camera._localDirection.copyFromFloats(0, 0, -speed);
  46629. }
  46630. if (camera.getScene().useRightHandedSystem) {
  46631. camera._localDirection.z *= -1;
  46632. }
  46633. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46634. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46635. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46636. }
  46637. }
  46638. };
  46639. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46640. return "FreeCameraKeyboardMoveInput";
  46641. };
  46642. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46643. this._keys = [];
  46644. };
  46645. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46646. return "keyboard";
  46647. };
  46648. __decorate([
  46649. BABYLON.serialize()
  46650. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46651. __decorate([
  46652. BABYLON.serialize()
  46653. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46654. __decorate([
  46655. BABYLON.serialize()
  46656. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46657. __decorate([
  46658. BABYLON.serialize()
  46659. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46660. return FreeCameraKeyboardMoveInput;
  46661. }());
  46662. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46663. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46664. })(BABYLON || (BABYLON = {}));
  46665. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46666. var BABYLON;
  46667. (function (BABYLON) {
  46668. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46669. __extends(FreeCameraInputsManager, _super);
  46670. function FreeCameraInputsManager(camera) {
  46671. return _super.call(this, camera) || this;
  46672. }
  46673. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46674. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46675. return this;
  46676. };
  46677. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46678. if (touchEnabled === void 0) { touchEnabled = true; }
  46679. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46680. return this;
  46681. };
  46682. FreeCameraInputsManager.prototype.addGamepad = function () {
  46683. this.add(new BABYLON.FreeCameraGamepadInput());
  46684. return this;
  46685. };
  46686. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46687. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46688. return this;
  46689. };
  46690. FreeCameraInputsManager.prototype.addTouch = function () {
  46691. this.add(new BABYLON.FreeCameraTouchInput());
  46692. return this;
  46693. };
  46694. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46695. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46696. return this;
  46697. };
  46698. return FreeCameraInputsManager;
  46699. }(BABYLON.CameraInputsManager));
  46700. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46701. })(BABYLON || (BABYLON = {}));
  46702. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46703. var BABYLON;
  46704. (function (BABYLON) {
  46705. var FreeCamera = /** @class */ (function (_super) {
  46706. __extends(FreeCamera, _super);
  46707. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46708. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46709. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46710. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46711. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46712. _this.checkCollisions = false;
  46713. _this.applyGravity = false;
  46714. _this._needMoveForGravity = false;
  46715. _this._oldPosition = BABYLON.Vector3.Zero();
  46716. _this._diffPosition = BABYLON.Vector3.Zero();
  46717. _this._newPosition = BABYLON.Vector3.Zero();
  46718. // Collisions
  46719. _this._collisionMask = -1;
  46720. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46721. if (collidedMesh === void 0) { collidedMesh = null; }
  46722. //TODO move this to the collision coordinator!
  46723. if (_this.getScene().workerCollisions)
  46724. newPosition.multiplyInPlace(_this._collider._radius);
  46725. var updatePosition = function (newPos) {
  46726. _this._newPosition.copyFrom(newPos);
  46727. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46728. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46729. _this.position.addInPlace(_this._diffPosition);
  46730. if (_this.onCollide && collidedMesh) {
  46731. _this.onCollide(collidedMesh);
  46732. }
  46733. }
  46734. };
  46735. updatePosition(newPosition);
  46736. };
  46737. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46738. _this.inputs.addKeyboard().addMouse();
  46739. return _this;
  46740. }
  46741. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46742. //-- begin properties for backward compatibility for inputs
  46743. /**
  46744. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46745. * Higher values reduce sensitivity.
  46746. */
  46747. get: function () {
  46748. var mouse = this.inputs.attached["mouse"];
  46749. if (mouse)
  46750. return mouse.angularSensibility;
  46751. return 0;
  46752. },
  46753. /**
  46754. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46755. * Higher values reduce sensitivity.
  46756. */
  46757. set: function (value) {
  46758. var mouse = this.inputs.attached["mouse"];
  46759. if (mouse)
  46760. mouse.angularSensibility = value;
  46761. },
  46762. enumerable: true,
  46763. configurable: true
  46764. });
  46765. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46766. get: function () {
  46767. var keyboard = this.inputs.attached["keyboard"];
  46768. if (keyboard)
  46769. return keyboard.keysUp;
  46770. return [];
  46771. },
  46772. set: function (value) {
  46773. var keyboard = this.inputs.attached["keyboard"];
  46774. if (keyboard)
  46775. keyboard.keysUp = value;
  46776. },
  46777. enumerable: true,
  46778. configurable: true
  46779. });
  46780. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46781. get: function () {
  46782. var keyboard = this.inputs.attached["keyboard"];
  46783. if (keyboard)
  46784. return keyboard.keysDown;
  46785. return [];
  46786. },
  46787. set: function (value) {
  46788. var keyboard = this.inputs.attached["keyboard"];
  46789. if (keyboard)
  46790. keyboard.keysDown = value;
  46791. },
  46792. enumerable: true,
  46793. configurable: true
  46794. });
  46795. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46796. get: function () {
  46797. var keyboard = this.inputs.attached["keyboard"];
  46798. if (keyboard)
  46799. return keyboard.keysLeft;
  46800. return [];
  46801. },
  46802. set: function (value) {
  46803. var keyboard = this.inputs.attached["keyboard"];
  46804. if (keyboard)
  46805. keyboard.keysLeft = value;
  46806. },
  46807. enumerable: true,
  46808. configurable: true
  46809. });
  46810. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46811. get: function () {
  46812. var keyboard = this.inputs.attached["keyboard"];
  46813. if (keyboard)
  46814. return keyboard.keysRight;
  46815. return [];
  46816. },
  46817. set: function (value) {
  46818. var keyboard = this.inputs.attached["keyboard"];
  46819. if (keyboard)
  46820. keyboard.keysRight = value;
  46821. },
  46822. enumerable: true,
  46823. configurable: true
  46824. });
  46825. // Controls
  46826. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46827. this.inputs.attachElement(element, noPreventDefault);
  46828. };
  46829. FreeCamera.prototype.detachControl = function (element) {
  46830. this.inputs.detachElement(element);
  46831. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46832. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46833. };
  46834. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46835. get: function () {
  46836. return this._collisionMask;
  46837. },
  46838. set: function (mask) {
  46839. this._collisionMask = !isNaN(mask) ? mask : -1;
  46840. },
  46841. enumerable: true,
  46842. configurable: true
  46843. });
  46844. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46845. var globalPosition;
  46846. if (this.parent) {
  46847. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46848. }
  46849. else {
  46850. globalPosition = this.position;
  46851. }
  46852. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46853. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46854. if (!this._collider) {
  46855. this._collider = new BABYLON.Collider();
  46856. }
  46857. this._collider._radius = this.ellipsoid;
  46858. this._collider.collisionMask = this._collisionMask;
  46859. //no need for clone, as long as gravity is not on.
  46860. var actualDisplacement = displacement;
  46861. //add gravity to the direction to prevent the dual-collision checking
  46862. if (this.applyGravity) {
  46863. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46864. actualDisplacement = displacement.add(this.getScene().gravity);
  46865. }
  46866. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46867. };
  46868. FreeCamera.prototype._checkInputs = function () {
  46869. if (!this._localDirection) {
  46870. this._localDirection = BABYLON.Vector3.Zero();
  46871. this._transformedDirection = BABYLON.Vector3.Zero();
  46872. }
  46873. this.inputs.checkInputs();
  46874. _super.prototype._checkInputs.call(this);
  46875. };
  46876. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46877. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46878. };
  46879. FreeCamera.prototype._updatePosition = function () {
  46880. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46881. this._collideWithWorld(this.cameraDirection);
  46882. }
  46883. else {
  46884. _super.prototype._updatePosition.call(this);
  46885. }
  46886. };
  46887. FreeCamera.prototype.dispose = function () {
  46888. this.inputs.clear();
  46889. _super.prototype.dispose.call(this);
  46890. };
  46891. FreeCamera.prototype.getClassName = function () {
  46892. return "FreeCamera";
  46893. };
  46894. __decorate([
  46895. BABYLON.serializeAsVector3()
  46896. ], FreeCamera.prototype, "ellipsoid", void 0);
  46897. __decorate([
  46898. BABYLON.serializeAsVector3()
  46899. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46900. __decorate([
  46901. BABYLON.serialize()
  46902. ], FreeCamera.prototype, "checkCollisions", void 0);
  46903. __decorate([
  46904. BABYLON.serialize()
  46905. ], FreeCamera.prototype, "applyGravity", void 0);
  46906. return FreeCamera;
  46907. }(BABYLON.TargetCamera));
  46908. BABYLON.FreeCamera = FreeCamera;
  46909. })(BABYLON || (BABYLON = {}));
  46910. //# sourceMappingURL=babylon.freeCamera.js.map
  46911. var BABYLON;
  46912. (function (BABYLON) {
  46913. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46914. function ArcRotateCameraKeyboardMoveInput() {
  46915. this._keys = new Array();
  46916. this.keysUp = [38];
  46917. this.keysDown = [40];
  46918. this.keysLeft = [37];
  46919. this.keysRight = [39];
  46920. this.keysReset = [220];
  46921. this.panningSensibility = 50.0;
  46922. this.zoomingSensibility = 25.0;
  46923. this.useAltToZoom = true;
  46924. }
  46925. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46926. var _this = this;
  46927. if (this._onCanvasBlurObserver) {
  46928. return;
  46929. }
  46930. this._scene = this.camera.getScene();
  46931. this._engine = this._scene.getEngine();
  46932. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46933. _this._keys = [];
  46934. });
  46935. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46936. var evt = info.event;
  46937. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46938. _this._ctrlPressed = evt.ctrlKey;
  46939. _this._altPressed = evt.altKey;
  46940. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46941. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46942. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46943. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46944. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46945. var index = _this._keys.indexOf(evt.keyCode);
  46946. if (index === -1) {
  46947. _this._keys.push(evt.keyCode);
  46948. }
  46949. if (evt.preventDefault) {
  46950. if (!noPreventDefault) {
  46951. evt.preventDefault();
  46952. }
  46953. }
  46954. }
  46955. }
  46956. else {
  46957. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46958. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46959. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46960. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46961. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46962. var index = _this._keys.indexOf(evt.keyCode);
  46963. if (index >= 0) {
  46964. _this._keys.splice(index, 1);
  46965. }
  46966. if (evt.preventDefault) {
  46967. if (!noPreventDefault) {
  46968. evt.preventDefault();
  46969. }
  46970. }
  46971. }
  46972. }
  46973. });
  46974. };
  46975. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46976. if (this._scene) {
  46977. if (this._onKeyboardObserver) {
  46978. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46979. }
  46980. if (this._onCanvasBlurObserver) {
  46981. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46982. }
  46983. this._onKeyboardObserver = null;
  46984. this._onCanvasBlurObserver = null;
  46985. }
  46986. this._keys = [];
  46987. };
  46988. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46989. if (this._onKeyboardObserver) {
  46990. var camera = this.camera;
  46991. for (var index = 0; index < this._keys.length; index++) {
  46992. var keyCode = this._keys[index];
  46993. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46994. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46995. camera.inertialPanningX -= 1 / this.panningSensibility;
  46996. }
  46997. else {
  46998. camera.inertialAlphaOffset -= 0.01;
  46999. }
  47000. }
  47001. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47002. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47003. camera.inertialPanningY += 1 / this.panningSensibility;
  47004. }
  47005. else if (this._altPressed && this.useAltToZoom) {
  47006. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47007. }
  47008. else {
  47009. camera.inertialBetaOffset -= 0.01;
  47010. }
  47011. }
  47012. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47013. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47014. camera.inertialPanningX += 1 / this.panningSensibility;
  47015. }
  47016. else {
  47017. camera.inertialAlphaOffset += 0.01;
  47018. }
  47019. }
  47020. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47021. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47022. camera.inertialPanningY -= 1 / this.panningSensibility;
  47023. }
  47024. else if (this._altPressed && this.useAltToZoom) {
  47025. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47026. }
  47027. else {
  47028. camera.inertialBetaOffset += 0.01;
  47029. }
  47030. }
  47031. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47032. camera.restoreState();
  47033. }
  47034. }
  47035. }
  47036. };
  47037. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47038. return "ArcRotateCameraKeyboardMoveInput";
  47039. };
  47040. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47041. return "keyboard";
  47042. };
  47043. __decorate([
  47044. BABYLON.serialize()
  47045. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47046. __decorate([
  47047. BABYLON.serialize()
  47048. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47049. __decorate([
  47050. BABYLON.serialize()
  47051. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47052. __decorate([
  47053. BABYLON.serialize()
  47054. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47055. __decorate([
  47056. BABYLON.serialize()
  47057. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47058. __decorate([
  47059. BABYLON.serialize()
  47060. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47061. __decorate([
  47062. BABYLON.serialize()
  47063. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47064. __decorate([
  47065. BABYLON.serialize()
  47066. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47067. return ArcRotateCameraKeyboardMoveInput;
  47068. }());
  47069. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47070. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47071. })(BABYLON || (BABYLON = {}));
  47072. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47073. var BABYLON;
  47074. (function (BABYLON) {
  47075. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47076. function ArcRotateCameraMouseWheelInput() {
  47077. this.wheelPrecision = 3.0;
  47078. /**
  47079. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47080. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47081. */
  47082. this.wheelDeltaPercentage = 0;
  47083. }
  47084. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47085. var _this = this;
  47086. this._wheel = function (p, s) {
  47087. //sanity check - this should be a PointerWheel event.
  47088. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47089. return;
  47090. var event = p.event;
  47091. var delta = 0;
  47092. if (event.wheelDelta) {
  47093. if (_this.wheelDeltaPercentage) {
  47094. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47095. if (event.wheelDelta > 0) {
  47096. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47097. }
  47098. else {
  47099. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47100. }
  47101. }
  47102. else {
  47103. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47104. }
  47105. }
  47106. else if (event.detail) {
  47107. delta = -event.detail / _this.wheelPrecision;
  47108. }
  47109. if (delta)
  47110. _this.camera.inertialRadiusOffset += delta;
  47111. if (event.preventDefault) {
  47112. if (!noPreventDefault) {
  47113. event.preventDefault();
  47114. }
  47115. }
  47116. };
  47117. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47118. };
  47119. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47120. if (this._observer && element) {
  47121. this.camera.getScene().onPointerObservable.remove(this._observer);
  47122. this._observer = null;
  47123. this._wheel = null;
  47124. }
  47125. };
  47126. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47127. return "ArcRotateCameraMouseWheelInput";
  47128. };
  47129. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47130. return "mousewheel";
  47131. };
  47132. __decorate([
  47133. BABYLON.serialize()
  47134. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47135. __decorate([
  47136. BABYLON.serialize()
  47137. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47138. return ArcRotateCameraMouseWheelInput;
  47139. }());
  47140. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47141. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47142. })(BABYLON || (BABYLON = {}));
  47143. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47144. var BABYLON;
  47145. (function (BABYLON) {
  47146. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47147. function ArcRotateCameraPointersInput() {
  47148. this.buttons = [0, 1, 2];
  47149. this.angularSensibilityX = 1000.0;
  47150. this.angularSensibilityY = 1000.0;
  47151. this.pinchPrecision = 12.0;
  47152. /**
  47153. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47154. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47155. */
  47156. this.pinchDeltaPercentage = 0;
  47157. this.panningSensibility = 1000.0;
  47158. this.multiTouchPanning = true;
  47159. this.multiTouchPanAndZoom = true;
  47160. this._isPanClick = false;
  47161. this.pinchInwards = true;
  47162. }
  47163. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47164. var _this = this;
  47165. var engine = this.camera.getEngine();
  47166. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47167. var pointA = null;
  47168. var pointB = null;
  47169. var previousPinchSquaredDistance = 0;
  47170. var initialDistance = 0;
  47171. var twoFingerActivityCount = 0;
  47172. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47173. this._pointerInput = function (p, s) {
  47174. var evt = p.event;
  47175. var isTouch = p.event.pointerType === "touch";
  47176. if (engine.isInVRExclusivePointerMode) {
  47177. return;
  47178. }
  47179. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47180. return;
  47181. }
  47182. var srcElement = (evt.srcElement || evt.target);
  47183. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47184. try {
  47185. srcElement.setPointerCapture(evt.pointerId);
  47186. }
  47187. catch (e) {
  47188. //Nothing to do with the error. Execution will continue.
  47189. }
  47190. // Manage panning with pan button click
  47191. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47192. // manage pointers
  47193. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47194. if (pointA === null) {
  47195. pointA = cacheSoloPointer;
  47196. }
  47197. else if (pointB === null) {
  47198. pointB = cacheSoloPointer;
  47199. }
  47200. if (!noPreventDefault) {
  47201. evt.preventDefault();
  47202. element.focus();
  47203. }
  47204. }
  47205. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47206. _this.camera.restoreState();
  47207. }
  47208. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47209. try {
  47210. srcElement.releasePointerCapture(evt.pointerId);
  47211. }
  47212. catch (e) {
  47213. //Nothing to do with the error.
  47214. }
  47215. cacheSoloPointer = null;
  47216. previousPinchSquaredDistance = 0;
  47217. previousMultiTouchPanPosition.isPaning = false;
  47218. previousMultiTouchPanPosition.isPinching = false;
  47219. twoFingerActivityCount = 0;
  47220. initialDistance = 0;
  47221. if (!isTouch) {
  47222. pointB = null; // Mouse and pen are mono pointer
  47223. }
  47224. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47225. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47226. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47227. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47228. if (engine._badOS) {
  47229. pointA = pointB = null;
  47230. }
  47231. else {
  47232. //only remove the impacted pointer in case of multitouch allowing on most
  47233. //platforms switching from rotate to zoom and pan seamlessly.
  47234. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47235. pointA = pointB;
  47236. pointB = null;
  47237. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47238. }
  47239. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47240. pointB = null;
  47241. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47242. }
  47243. else {
  47244. pointA = pointB = null;
  47245. }
  47246. }
  47247. if (!noPreventDefault) {
  47248. evt.preventDefault();
  47249. }
  47250. }
  47251. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47252. if (!noPreventDefault) {
  47253. evt.preventDefault();
  47254. }
  47255. // One button down
  47256. if (pointA && pointB === null && cacheSoloPointer) {
  47257. if (_this.panningSensibility !== 0 &&
  47258. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47259. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47260. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47261. }
  47262. else {
  47263. var offsetX = evt.clientX - cacheSoloPointer.x;
  47264. var offsetY = evt.clientY - cacheSoloPointer.y;
  47265. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47266. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47267. }
  47268. cacheSoloPointer.x = evt.clientX;
  47269. cacheSoloPointer.y = evt.clientY;
  47270. }
  47271. // Two buttons down: pinch/pan
  47272. else if (pointA && pointB) {
  47273. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47274. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47275. ed.x = evt.clientX;
  47276. ed.y = evt.clientY;
  47277. var direction = _this.pinchInwards ? 1 : -1;
  47278. var distX = pointA.x - pointB.x;
  47279. var distY = pointA.y - pointB.y;
  47280. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47281. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47282. if (previousPinchSquaredDistance === 0) {
  47283. initialDistance = pinchDistance;
  47284. previousPinchSquaredDistance = pinchSquaredDistance;
  47285. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47286. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47287. return;
  47288. }
  47289. if (_this.multiTouchPanAndZoom) {
  47290. if (_this.pinchDeltaPercentage) {
  47291. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47292. }
  47293. else {
  47294. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47295. (_this.pinchPrecision *
  47296. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47297. direction);
  47298. }
  47299. if (_this.panningSensibility !== 0) {
  47300. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47301. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47302. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47303. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47304. previousMultiTouchPanPosition.x = pointersCenterX;
  47305. previousMultiTouchPanPosition.y = pointersCenterY;
  47306. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47307. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47308. }
  47309. }
  47310. else {
  47311. twoFingerActivityCount++;
  47312. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47313. if (_this.pinchDeltaPercentage) {
  47314. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47315. }
  47316. else {
  47317. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47318. (_this.pinchPrecision *
  47319. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47320. direction);
  47321. }
  47322. previousMultiTouchPanPosition.isPaning = false;
  47323. previousMultiTouchPanPosition.isPinching = true;
  47324. }
  47325. else {
  47326. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47327. if (!previousMultiTouchPanPosition.isPaning) {
  47328. previousMultiTouchPanPosition.isPaning = true;
  47329. previousMultiTouchPanPosition.isPinching = false;
  47330. previousMultiTouchPanPosition.x = ed.x;
  47331. previousMultiTouchPanPosition.y = ed.y;
  47332. return;
  47333. }
  47334. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47335. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47336. }
  47337. }
  47338. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47339. previousMultiTouchPanPosition.x = ed.x;
  47340. previousMultiTouchPanPosition.y = ed.y;
  47341. }
  47342. }
  47343. previousPinchSquaredDistance = pinchSquaredDistance;
  47344. }
  47345. }
  47346. };
  47347. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47348. this._onContextMenu = function (evt) {
  47349. evt.preventDefault();
  47350. };
  47351. if (!this.camera._useCtrlForPanning) {
  47352. element.addEventListener("contextmenu", this._onContextMenu, false);
  47353. }
  47354. this._onLostFocus = function () {
  47355. //this._keys = [];
  47356. pointA = pointB = null;
  47357. previousPinchSquaredDistance = 0;
  47358. previousMultiTouchPanPosition.isPaning = false;
  47359. previousMultiTouchPanPosition.isPinching = false;
  47360. twoFingerActivityCount = 0;
  47361. cacheSoloPointer = null;
  47362. initialDistance = 0;
  47363. };
  47364. this._onMouseMove = function (evt) {
  47365. if (!engine.isPointerLock) {
  47366. return;
  47367. }
  47368. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47369. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47370. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47371. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47372. if (!noPreventDefault) {
  47373. evt.preventDefault();
  47374. }
  47375. };
  47376. this._onGestureStart = function (e) {
  47377. if (window.MSGesture === undefined) {
  47378. return;
  47379. }
  47380. if (!_this._MSGestureHandler) {
  47381. _this._MSGestureHandler = new MSGesture();
  47382. _this._MSGestureHandler.target = element;
  47383. }
  47384. _this._MSGestureHandler.addPointer(e.pointerId);
  47385. };
  47386. this._onGesture = function (e) {
  47387. _this.camera.radius *= e.scale;
  47388. if (e.preventDefault) {
  47389. if (!noPreventDefault) {
  47390. e.stopPropagation();
  47391. e.preventDefault();
  47392. }
  47393. }
  47394. };
  47395. element.addEventListener("mousemove", this._onMouseMove, false);
  47396. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47397. element.addEventListener("MSGestureChange", this._onGesture, false);
  47398. BABYLON.Tools.RegisterTopRootEvents([
  47399. { name: "blur", handler: this._onLostFocus }
  47400. ]);
  47401. };
  47402. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47403. if (this._onLostFocus) {
  47404. BABYLON.Tools.UnregisterTopRootEvents([
  47405. { name: "blur", handler: this._onLostFocus }
  47406. ]);
  47407. }
  47408. if (element && this._observer) {
  47409. this.camera.getScene().onPointerObservable.remove(this._observer);
  47410. this._observer = null;
  47411. if (this._onContextMenu) {
  47412. element.removeEventListener("contextmenu", this._onContextMenu);
  47413. }
  47414. if (this._onMouseMove) {
  47415. element.removeEventListener("mousemove", this._onMouseMove);
  47416. }
  47417. if (this._onGestureStart) {
  47418. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47419. }
  47420. if (this._onGesture) {
  47421. element.removeEventListener("MSGestureChange", this._onGesture);
  47422. }
  47423. this._isPanClick = false;
  47424. this.pinchInwards = true;
  47425. this._onMouseMove = null;
  47426. this._onGestureStart = null;
  47427. this._onGesture = null;
  47428. this._MSGestureHandler = null;
  47429. this._onLostFocus = null;
  47430. this._onContextMenu = null;
  47431. }
  47432. };
  47433. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47434. return "ArcRotateCameraPointersInput";
  47435. };
  47436. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47437. return "pointers";
  47438. };
  47439. __decorate([
  47440. BABYLON.serialize()
  47441. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47442. __decorate([
  47443. BABYLON.serialize()
  47444. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47445. __decorate([
  47446. BABYLON.serialize()
  47447. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47448. __decorate([
  47449. BABYLON.serialize()
  47450. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47451. __decorate([
  47452. BABYLON.serialize()
  47453. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47454. __decorate([
  47455. BABYLON.serialize()
  47456. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47457. __decorate([
  47458. BABYLON.serialize()
  47459. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47460. __decorate([
  47461. BABYLON.serialize()
  47462. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47463. return ArcRotateCameraPointersInput;
  47464. }());
  47465. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47466. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47467. })(BABYLON || (BABYLON = {}));
  47468. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47469. var BABYLON;
  47470. (function (BABYLON) {
  47471. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47472. __extends(ArcRotateCameraInputsManager, _super);
  47473. function ArcRotateCameraInputsManager(camera) {
  47474. return _super.call(this, camera) || this;
  47475. }
  47476. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47477. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47478. return this;
  47479. };
  47480. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47481. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47482. return this;
  47483. };
  47484. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47485. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47486. return this;
  47487. };
  47488. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47489. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47490. return this;
  47491. };
  47492. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47493. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47494. return this;
  47495. };
  47496. return ArcRotateCameraInputsManager;
  47497. }(BABYLON.CameraInputsManager));
  47498. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47499. })(BABYLON || (BABYLON = {}));
  47500. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47501. var BABYLON;
  47502. (function (BABYLON) {
  47503. var ArcRotateCamera = /** @class */ (function (_super) {
  47504. __extends(ArcRotateCamera, _super);
  47505. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47506. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47507. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47508. _this.inertialAlphaOffset = 0;
  47509. _this.inertialBetaOffset = 0;
  47510. _this.inertialRadiusOffset = 0;
  47511. _this.lowerAlphaLimit = null;
  47512. _this.upperAlphaLimit = null;
  47513. _this.lowerBetaLimit = 0.01;
  47514. _this.upperBetaLimit = Math.PI;
  47515. _this.lowerRadiusLimit = null;
  47516. _this.upperRadiusLimit = null;
  47517. _this.inertialPanningX = 0;
  47518. _this.inertialPanningY = 0;
  47519. _this.pinchToPanMaxDistance = 20;
  47520. _this.panningDistanceLimit = null;
  47521. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47522. _this.panningInertia = 0.9;
  47523. //-- end properties for backward compatibility for inputs
  47524. _this.zoomOnFactor = 1;
  47525. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47526. _this.allowUpsideDown = true;
  47527. _this._viewMatrix = new BABYLON.Matrix();
  47528. // Panning
  47529. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47530. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47531. _this.checkCollisions = false;
  47532. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47533. _this._previousPosition = BABYLON.Vector3.Zero();
  47534. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47535. _this._newPosition = BABYLON.Vector3.Zero();
  47536. _this._computationVector = BABYLON.Vector3.Zero();
  47537. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47538. if (collidedMesh === void 0) { collidedMesh = null; }
  47539. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47540. newPosition.multiplyInPlace(_this._collider._radius);
  47541. }
  47542. if (!collidedMesh) {
  47543. _this._previousPosition.copyFrom(_this.position);
  47544. }
  47545. else {
  47546. _this.setPosition(newPosition);
  47547. if (_this.onCollide) {
  47548. _this.onCollide(collidedMesh);
  47549. }
  47550. }
  47551. // Recompute because of constraints
  47552. var cosa = Math.cos(_this.alpha);
  47553. var sina = Math.sin(_this.alpha);
  47554. var cosb = Math.cos(_this.beta);
  47555. var sinb = Math.sin(_this.beta);
  47556. if (sinb === 0) {
  47557. sinb = 0.0001;
  47558. }
  47559. var target = _this._getTargetPosition();
  47560. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47561. target.addToRef(_this._computationVector, _this._newPosition);
  47562. _this.position.copyFrom(_this._newPosition);
  47563. var up = _this.upVector;
  47564. if (_this.allowUpsideDown && _this.beta < 0) {
  47565. up = up.clone();
  47566. up = up.negate();
  47567. }
  47568. _this._computeViewMatrix(_this.position, target, up);
  47569. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47570. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47571. _this._collisionTriggered = false;
  47572. };
  47573. _this._target = BABYLON.Vector3.Zero();
  47574. if (target) {
  47575. _this.setTarget(target);
  47576. }
  47577. _this.alpha = alpha;
  47578. _this.beta = beta;
  47579. _this.radius = radius;
  47580. _this.getViewMatrix();
  47581. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47582. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47583. return _this;
  47584. }
  47585. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47586. get: function () {
  47587. return this._target;
  47588. },
  47589. set: function (value) {
  47590. this.setTarget(value);
  47591. },
  47592. enumerable: true,
  47593. configurable: true
  47594. });
  47595. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47596. //-- begin properties for backward compatibility for inputs
  47597. get: function () {
  47598. var pointers = this.inputs.attached["pointers"];
  47599. if (pointers)
  47600. return pointers.angularSensibilityX;
  47601. return 0;
  47602. },
  47603. set: function (value) {
  47604. var pointers = this.inputs.attached["pointers"];
  47605. if (pointers) {
  47606. pointers.angularSensibilityX = value;
  47607. }
  47608. },
  47609. enumerable: true,
  47610. configurable: true
  47611. });
  47612. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47613. get: function () {
  47614. var pointers = this.inputs.attached["pointers"];
  47615. if (pointers)
  47616. return pointers.angularSensibilityY;
  47617. return 0;
  47618. },
  47619. set: function (value) {
  47620. var pointers = this.inputs.attached["pointers"];
  47621. if (pointers) {
  47622. pointers.angularSensibilityY = value;
  47623. }
  47624. },
  47625. enumerable: true,
  47626. configurable: true
  47627. });
  47628. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47629. get: function () {
  47630. var pointers = this.inputs.attached["pointers"];
  47631. if (pointers)
  47632. return pointers.pinchPrecision;
  47633. return 0;
  47634. },
  47635. set: function (value) {
  47636. var pointers = this.inputs.attached["pointers"];
  47637. if (pointers) {
  47638. pointers.pinchPrecision = value;
  47639. }
  47640. },
  47641. enumerable: true,
  47642. configurable: true
  47643. });
  47644. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47645. get: function () {
  47646. var pointers = this.inputs.attached["pointers"];
  47647. if (pointers)
  47648. return pointers.pinchDeltaPercentage;
  47649. return 0;
  47650. },
  47651. set: function (value) {
  47652. var pointers = this.inputs.attached["pointers"];
  47653. if (pointers) {
  47654. pointers.pinchDeltaPercentage = value;
  47655. }
  47656. },
  47657. enumerable: true,
  47658. configurable: true
  47659. });
  47660. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47661. get: function () {
  47662. var pointers = this.inputs.attached["pointers"];
  47663. if (pointers)
  47664. return pointers.panningSensibility;
  47665. return 0;
  47666. },
  47667. set: function (value) {
  47668. var pointers = this.inputs.attached["pointers"];
  47669. if (pointers) {
  47670. pointers.panningSensibility = value;
  47671. }
  47672. },
  47673. enumerable: true,
  47674. configurable: true
  47675. });
  47676. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47677. get: function () {
  47678. var keyboard = this.inputs.attached["keyboard"];
  47679. if (keyboard)
  47680. return keyboard.keysUp;
  47681. return [];
  47682. },
  47683. set: function (value) {
  47684. var keyboard = this.inputs.attached["keyboard"];
  47685. if (keyboard)
  47686. keyboard.keysUp = value;
  47687. },
  47688. enumerable: true,
  47689. configurable: true
  47690. });
  47691. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47692. get: function () {
  47693. var keyboard = this.inputs.attached["keyboard"];
  47694. if (keyboard)
  47695. return keyboard.keysDown;
  47696. return [];
  47697. },
  47698. set: function (value) {
  47699. var keyboard = this.inputs.attached["keyboard"];
  47700. if (keyboard)
  47701. keyboard.keysDown = value;
  47702. },
  47703. enumerable: true,
  47704. configurable: true
  47705. });
  47706. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47707. get: function () {
  47708. var keyboard = this.inputs.attached["keyboard"];
  47709. if (keyboard)
  47710. return keyboard.keysLeft;
  47711. return [];
  47712. },
  47713. set: function (value) {
  47714. var keyboard = this.inputs.attached["keyboard"];
  47715. if (keyboard)
  47716. keyboard.keysLeft = value;
  47717. },
  47718. enumerable: true,
  47719. configurable: true
  47720. });
  47721. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47722. get: function () {
  47723. var keyboard = this.inputs.attached["keyboard"];
  47724. if (keyboard)
  47725. return keyboard.keysRight;
  47726. return [];
  47727. },
  47728. set: function (value) {
  47729. var keyboard = this.inputs.attached["keyboard"];
  47730. if (keyboard)
  47731. keyboard.keysRight = value;
  47732. },
  47733. enumerable: true,
  47734. configurable: true
  47735. });
  47736. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47737. get: function () {
  47738. var mousewheel = this.inputs.attached["mousewheel"];
  47739. if (mousewheel)
  47740. return mousewheel.wheelPrecision;
  47741. return 0;
  47742. },
  47743. set: function (value) {
  47744. var mousewheel = this.inputs.attached["mousewheel"];
  47745. if (mousewheel)
  47746. mousewheel.wheelPrecision = value;
  47747. },
  47748. enumerable: true,
  47749. configurable: true
  47750. });
  47751. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47752. get: function () {
  47753. var mousewheel = this.inputs.attached["mousewheel"];
  47754. if (mousewheel)
  47755. return mousewheel.wheelDeltaPercentage;
  47756. return 0;
  47757. },
  47758. set: function (value) {
  47759. var mousewheel = this.inputs.attached["mousewheel"];
  47760. if (mousewheel)
  47761. mousewheel.wheelDeltaPercentage = value;
  47762. },
  47763. enumerable: true,
  47764. configurable: true
  47765. });
  47766. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47767. get: function () {
  47768. return this._bouncingBehavior;
  47769. },
  47770. enumerable: true,
  47771. configurable: true
  47772. });
  47773. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47774. get: function () {
  47775. return this._bouncingBehavior != null;
  47776. },
  47777. set: function (value) {
  47778. if (value === this.useBouncingBehavior) {
  47779. return;
  47780. }
  47781. if (value) {
  47782. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47783. this.addBehavior(this._bouncingBehavior);
  47784. }
  47785. else if (this._bouncingBehavior) {
  47786. this.removeBehavior(this._bouncingBehavior);
  47787. this._bouncingBehavior = null;
  47788. }
  47789. },
  47790. enumerable: true,
  47791. configurable: true
  47792. });
  47793. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47794. get: function () {
  47795. return this._framingBehavior;
  47796. },
  47797. enumerable: true,
  47798. configurable: true
  47799. });
  47800. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47801. get: function () {
  47802. return this._framingBehavior != null;
  47803. },
  47804. set: function (value) {
  47805. if (value === this.useFramingBehavior) {
  47806. return;
  47807. }
  47808. if (value) {
  47809. this._framingBehavior = new BABYLON.FramingBehavior();
  47810. this.addBehavior(this._framingBehavior);
  47811. }
  47812. else if (this._framingBehavior) {
  47813. this.removeBehavior(this._framingBehavior);
  47814. this._framingBehavior = null;
  47815. }
  47816. },
  47817. enumerable: true,
  47818. configurable: true
  47819. });
  47820. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47821. get: function () {
  47822. return this._autoRotationBehavior;
  47823. },
  47824. enumerable: true,
  47825. configurable: true
  47826. });
  47827. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47828. get: function () {
  47829. return this._autoRotationBehavior != null;
  47830. },
  47831. set: function (value) {
  47832. if (value === this.useAutoRotationBehavior) {
  47833. return;
  47834. }
  47835. if (value) {
  47836. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47837. this.addBehavior(this._autoRotationBehavior);
  47838. }
  47839. else if (this._autoRotationBehavior) {
  47840. this.removeBehavior(this._autoRotationBehavior);
  47841. this._autoRotationBehavior = null;
  47842. }
  47843. },
  47844. enumerable: true,
  47845. configurable: true
  47846. });
  47847. // Cache
  47848. ArcRotateCamera.prototype._initCache = function () {
  47849. _super.prototype._initCache.call(this);
  47850. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47851. this._cache.alpha = undefined;
  47852. this._cache.beta = undefined;
  47853. this._cache.radius = undefined;
  47854. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47855. };
  47856. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47857. if (!ignoreParentClass) {
  47858. _super.prototype._updateCache.call(this);
  47859. }
  47860. this._cache._target.copyFrom(this._getTargetPosition());
  47861. this._cache.alpha = this.alpha;
  47862. this._cache.beta = this.beta;
  47863. this._cache.radius = this.radius;
  47864. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47865. };
  47866. ArcRotateCamera.prototype._getTargetPosition = function () {
  47867. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47868. var pos = this._targetHost.getAbsolutePosition();
  47869. if (this._targetBoundingCenter) {
  47870. pos.addToRef(this._targetBoundingCenter, this._target);
  47871. }
  47872. else {
  47873. this._target.copyFrom(pos);
  47874. }
  47875. }
  47876. var lockedTargetPosition = this._getLockedTargetPosition();
  47877. if (lockedTargetPosition) {
  47878. return lockedTargetPosition;
  47879. }
  47880. return this._target;
  47881. };
  47882. ArcRotateCamera.prototype.storeState = function () {
  47883. this._storedAlpha = this.alpha;
  47884. this._storedBeta = this.beta;
  47885. this._storedRadius = this.radius;
  47886. this._storedTarget = this._getTargetPosition().clone();
  47887. return _super.prototype.storeState.call(this);
  47888. };
  47889. /**
  47890. * Restored camera state. You must call storeState() first
  47891. */
  47892. ArcRotateCamera.prototype._restoreStateValues = function () {
  47893. if (!_super.prototype._restoreStateValues.call(this)) {
  47894. return false;
  47895. }
  47896. this.alpha = this._storedAlpha;
  47897. this.beta = this._storedBeta;
  47898. this.radius = this._storedRadius;
  47899. this.setTarget(this._storedTarget.clone());
  47900. this.inertialAlphaOffset = 0;
  47901. this.inertialBetaOffset = 0;
  47902. this.inertialRadiusOffset = 0;
  47903. this.inertialPanningX = 0;
  47904. this.inertialPanningY = 0;
  47905. return true;
  47906. };
  47907. // Synchronized
  47908. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47909. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47910. return false;
  47911. return this._cache._target.equals(this._getTargetPosition())
  47912. && this._cache.alpha === this.alpha
  47913. && this._cache.beta === this.beta
  47914. && this._cache.radius === this.radius
  47915. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47916. };
  47917. // Methods
  47918. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47919. var _this = this;
  47920. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47921. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47922. this._useCtrlForPanning = useCtrlForPanning;
  47923. this._panningMouseButton = panningMouseButton;
  47924. this.inputs.attachElement(element, noPreventDefault);
  47925. this._reset = function () {
  47926. _this.inertialAlphaOffset = 0;
  47927. _this.inertialBetaOffset = 0;
  47928. _this.inertialRadiusOffset = 0;
  47929. _this.inertialPanningX = 0;
  47930. _this.inertialPanningY = 0;
  47931. };
  47932. };
  47933. ArcRotateCamera.prototype.detachControl = function (element) {
  47934. this.inputs.detachElement(element);
  47935. if (this._reset) {
  47936. this._reset();
  47937. }
  47938. };
  47939. ArcRotateCamera.prototype._checkInputs = function () {
  47940. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47941. if (this._collisionTriggered) {
  47942. return;
  47943. }
  47944. this.inputs.checkInputs();
  47945. // Inertia
  47946. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47947. var inertialAlphaOffset = this.inertialAlphaOffset;
  47948. if (this.beta <= 0)
  47949. inertialAlphaOffset *= -1;
  47950. if (this.getScene().useRightHandedSystem)
  47951. inertialAlphaOffset *= -1;
  47952. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47953. inertialAlphaOffset *= -1;
  47954. this.alpha += inertialAlphaOffset;
  47955. this.beta += this.inertialBetaOffset;
  47956. this.radius -= this.inertialRadiusOffset;
  47957. this.inertialAlphaOffset *= this.inertia;
  47958. this.inertialBetaOffset *= this.inertia;
  47959. this.inertialRadiusOffset *= this.inertia;
  47960. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47961. this.inertialAlphaOffset = 0;
  47962. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47963. this.inertialBetaOffset = 0;
  47964. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47965. this.inertialRadiusOffset = 0;
  47966. }
  47967. // Panning inertia
  47968. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47969. if (!this._localDirection) {
  47970. this._localDirection = BABYLON.Vector3.Zero();
  47971. this._transformedDirection = BABYLON.Vector3.Zero();
  47972. }
  47973. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47974. this._localDirection.multiplyInPlace(this.panningAxis);
  47975. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47976. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47977. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47978. if (!this.panningAxis.y) {
  47979. this._transformedDirection.y = 0;
  47980. }
  47981. if (!this._targetHost) {
  47982. if (this.panningDistanceLimit) {
  47983. this._transformedDirection.addInPlace(this._target);
  47984. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47985. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47986. this._target.copyFrom(this._transformedDirection);
  47987. }
  47988. }
  47989. else {
  47990. this._target.addInPlace(this._transformedDirection);
  47991. }
  47992. }
  47993. this.inertialPanningX *= this.panningInertia;
  47994. this.inertialPanningY *= this.panningInertia;
  47995. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47996. this.inertialPanningX = 0;
  47997. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47998. this.inertialPanningY = 0;
  47999. }
  48000. // Limits
  48001. this._checkLimits();
  48002. _super.prototype._checkInputs.call(this);
  48003. };
  48004. ArcRotateCamera.prototype._checkLimits = function () {
  48005. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48006. if (this.allowUpsideDown && this.beta > Math.PI) {
  48007. this.beta = this.beta - (2 * Math.PI);
  48008. }
  48009. }
  48010. else {
  48011. if (this.beta < this.lowerBetaLimit) {
  48012. this.beta = this.lowerBetaLimit;
  48013. }
  48014. }
  48015. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48016. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48017. this.beta = this.beta + (2 * Math.PI);
  48018. }
  48019. }
  48020. else {
  48021. if (this.beta > this.upperBetaLimit) {
  48022. this.beta = this.upperBetaLimit;
  48023. }
  48024. }
  48025. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48026. this.alpha = this.lowerAlphaLimit;
  48027. }
  48028. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48029. this.alpha = this.upperAlphaLimit;
  48030. }
  48031. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48032. this.radius = this.lowerRadiusLimit;
  48033. }
  48034. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48035. this.radius = this.upperRadiusLimit;
  48036. }
  48037. };
  48038. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48039. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48040. this.radius = this._computationVector.length();
  48041. if (this.radius === 0) {
  48042. this.radius = 0.0001; // Just to avoid division by zero
  48043. }
  48044. // Alpha
  48045. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48046. if (this._computationVector.z < 0) {
  48047. this.alpha = 2 * Math.PI - this.alpha;
  48048. }
  48049. // Beta
  48050. this.beta = Math.acos(this._computationVector.y / this.radius);
  48051. this._checkLimits();
  48052. };
  48053. ArcRotateCamera.prototype.setPosition = function (position) {
  48054. if (this.position.equals(position)) {
  48055. return;
  48056. }
  48057. this.position.copyFrom(position);
  48058. this.rebuildAnglesAndRadius();
  48059. };
  48060. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48061. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48062. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48063. if (target.getBoundingInfo) {
  48064. if (toBoundingCenter) {
  48065. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48066. }
  48067. else {
  48068. this._targetBoundingCenter = null;
  48069. }
  48070. this._targetHost = target;
  48071. this._target = this._getTargetPosition();
  48072. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48073. }
  48074. else {
  48075. var newTarget = target;
  48076. var currentTarget = this._getTargetPosition();
  48077. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48078. return;
  48079. }
  48080. this._targetHost = null;
  48081. this._target = newTarget;
  48082. this._targetBoundingCenter = null;
  48083. this.onMeshTargetChangedObservable.notifyObservers(null);
  48084. }
  48085. this.rebuildAnglesAndRadius();
  48086. };
  48087. ArcRotateCamera.prototype._getViewMatrix = function () {
  48088. // Compute
  48089. var cosa = Math.cos(this.alpha);
  48090. var sina = Math.sin(this.alpha);
  48091. var cosb = Math.cos(this.beta);
  48092. var sinb = Math.sin(this.beta);
  48093. if (sinb === 0) {
  48094. sinb = 0.0001;
  48095. }
  48096. var target = this._getTargetPosition();
  48097. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48098. target.addToRef(this._computationVector, this._newPosition);
  48099. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48100. if (!this._collider) {
  48101. this._collider = new BABYLON.Collider();
  48102. }
  48103. this._collider._radius = this.collisionRadius;
  48104. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48105. this._collisionTriggered = true;
  48106. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48107. }
  48108. else {
  48109. this.position.copyFrom(this._newPosition);
  48110. var up = this.upVector;
  48111. if (this.allowUpsideDown && sinb < 0) {
  48112. up = up.clone();
  48113. up = up.negate();
  48114. }
  48115. this._computeViewMatrix(this.position, target, up);
  48116. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48117. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48118. }
  48119. this._currentTarget = target;
  48120. return this._viewMatrix;
  48121. };
  48122. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48123. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48124. meshes = meshes || this.getScene().meshes;
  48125. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48126. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48127. this.radius = distance * this.zoomOnFactor;
  48128. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48129. };
  48130. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48131. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48132. var meshesOrMinMaxVector;
  48133. var distance;
  48134. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48135. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48136. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48137. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48138. }
  48139. else { //minMaxVector and distance
  48140. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48141. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48142. distance = minMaxVectorAndDistance.distance;
  48143. }
  48144. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48145. if (!doNotUpdateMaxZ) {
  48146. this.maxZ = distance * 2;
  48147. }
  48148. };
  48149. /**
  48150. * @override
  48151. * Override Camera.createRigCamera
  48152. */
  48153. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48154. var alphaShift = 0;
  48155. switch (this.cameraRigMode) {
  48156. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48157. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48158. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48159. case BABYLON.Camera.RIG_MODE_VR:
  48160. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48161. break;
  48162. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48163. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48164. break;
  48165. }
  48166. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48167. rigCam._cameraRigParams = {};
  48168. return rigCam;
  48169. };
  48170. /**
  48171. * @override
  48172. * Override Camera._updateRigCameras
  48173. */
  48174. ArcRotateCamera.prototype._updateRigCameras = function () {
  48175. var camLeft = this._rigCameras[0];
  48176. var camRight = this._rigCameras[1];
  48177. camLeft.beta = camRight.beta = this.beta;
  48178. camLeft.radius = camRight.radius = this.radius;
  48179. switch (this.cameraRigMode) {
  48180. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48181. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48182. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48183. case BABYLON.Camera.RIG_MODE_VR:
  48184. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48185. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48186. break;
  48187. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48188. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48189. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48190. break;
  48191. }
  48192. _super.prototype._updateRigCameras.call(this);
  48193. };
  48194. ArcRotateCamera.prototype.dispose = function () {
  48195. this.inputs.clear();
  48196. _super.prototype.dispose.call(this);
  48197. };
  48198. ArcRotateCamera.prototype.getClassName = function () {
  48199. return "ArcRotateCamera";
  48200. };
  48201. __decorate([
  48202. BABYLON.serialize()
  48203. ], ArcRotateCamera.prototype, "alpha", void 0);
  48204. __decorate([
  48205. BABYLON.serialize()
  48206. ], ArcRotateCamera.prototype, "beta", void 0);
  48207. __decorate([
  48208. BABYLON.serialize()
  48209. ], ArcRotateCamera.prototype, "radius", void 0);
  48210. __decorate([
  48211. BABYLON.serializeAsVector3("target")
  48212. ], ArcRotateCamera.prototype, "_target", void 0);
  48213. __decorate([
  48214. BABYLON.serialize()
  48215. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48216. __decorate([
  48217. BABYLON.serialize()
  48218. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48219. __decorate([
  48220. BABYLON.serialize()
  48221. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48222. __decorate([
  48223. BABYLON.serialize()
  48224. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48225. __decorate([
  48226. BABYLON.serialize()
  48227. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48228. __decorate([
  48229. BABYLON.serialize()
  48230. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48231. __decorate([
  48232. BABYLON.serialize()
  48233. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48234. __decorate([
  48235. BABYLON.serialize()
  48236. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48237. __decorate([
  48238. BABYLON.serialize()
  48239. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48240. __decorate([
  48241. BABYLON.serialize()
  48242. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48243. __decorate([
  48244. BABYLON.serialize()
  48245. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48246. __decorate([
  48247. BABYLON.serialize()
  48248. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48249. __decorate([
  48250. BABYLON.serialize()
  48251. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48252. __decorate([
  48253. BABYLON.serializeAsVector3()
  48254. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48255. __decorate([
  48256. BABYLON.serialize()
  48257. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48258. __decorate([
  48259. BABYLON.serialize()
  48260. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48261. __decorate([
  48262. BABYLON.serialize()
  48263. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48264. return ArcRotateCamera;
  48265. }(BABYLON.TargetCamera));
  48266. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48267. })(BABYLON || (BABYLON = {}));
  48268. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48269. var BABYLON;
  48270. (function (BABYLON) {
  48271. /**
  48272. * The HemisphericLight simulates the ambient environment light,
  48273. * so the passed direction is the light reflection direction, not the incoming direction.
  48274. */
  48275. var HemisphericLight = /** @class */ (function (_super) {
  48276. __extends(HemisphericLight, _super);
  48277. /**
  48278. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48279. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48280. * The HemisphericLight can't cast shadows.
  48281. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48282. * @param name The friendly name of the light
  48283. * @param direction The direction of the light reflection
  48284. * @param scene The scene the light belongs to
  48285. */
  48286. function HemisphericLight(name, direction, scene) {
  48287. var _this = _super.call(this, name, scene) || this;
  48288. /**
  48289. * The groundColor is the light in the opposite direction to the one specified during creation.
  48290. * 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.
  48291. */
  48292. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48293. _this.direction = direction || BABYLON.Vector3.Up();
  48294. return _this;
  48295. }
  48296. HemisphericLight.prototype._buildUniformLayout = function () {
  48297. this._uniformBuffer.addUniform("vLightData", 4);
  48298. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48299. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48300. this._uniformBuffer.addUniform("vLightGround", 3);
  48301. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48302. this._uniformBuffer.addUniform("depthValues", 2);
  48303. this._uniformBuffer.create();
  48304. };
  48305. /**
  48306. * Returns the string "HemisphericLight".
  48307. * @return The class name
  48308. */
  48309. HemisphericLight.prototype.getClassName = function () {
  48310. return "HemisphericLight";
  48311. };
  48312. /**
  48313. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48314. * Returns the updated direction.
  48315. * @param target The target the direction should point to
  48316. * @return The computed direction
  48317. */
  48318. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48319. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48320. return this.direction;
  48321. };
  48322. /**
  48323. * Returns the shadow generator associated to the light.
  48324. * @returns Always null for hemispheric lights because it does not support shadows.
  48325. */
  48326. HemisphericLight.prototype.getShadowGenerator = function () {
  48327. return null;
  48328. };
  48329. /**
  48330. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48331. * @param effect The effect to update
  48332. * @param lightIndex The index of the light in the effect to update
  48333. * @returns The hemispheric light
  48334. */
  48335. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48336. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48337. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48338. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48339. return this;
  48340. };
  48341. /**
  48342. * @hidden internal use only.
  48343. */
  48344. HemisphericLight.prototype._getWorldMatrix = function () {
  48345. if (!this._worldMatrix) {
  48346. this._worldMatrix = BABYLON.Matrix.Identity();
  48347. }
  48348. return this._worldMatrix;
  48349. };
  48350. /**
  48351. * Returns the integer 3.
  48352. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48353. */
  48354. HemisphericLight.prototype.getTypeID = function () {
  48355. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48356. };
  48357. __decorate([
  48358. BABYLON.serializeAsColor3()
  48359. ], HemisphericLight.prototype, "groundColor", void 0);
  48360. __decorate([
  48361. BABYLON.serializeAsVector3()
  48362. ], HemisphericLight.prototype, "direction", void 0);
  48363. return HemisphericLight;
  48364. }(BABYLON.Light));
  48365. BABYLON.HemisphericLight = HemisphericLight;
  48366. })(BABYLON || (BABYLON = {}));
  48367. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48368. var BABYLON;
  48369. (function (BABYLON) {
  48370. /**
  48371. * Base implementation IShadowLight
  48372. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48373. */
  48374. var ShadowLight = /** @class */ (function (_super) {
  48375. __extends(ShadowLight, _super);
  48376. function ShadowLight() {
  48377. var _this = _super !== null && _super.apply(this, arguments) || this;
  48378. _this._needProjectionMatrixCompute = true;
  48379. return _this;
  48380. }
  48381. ShadowLight.prototype._setPosition = function (value) {
  48382. this._position = value;
  48383. };
  48384. Object.defineProperty(ShadowLight.prototype, "position", {
  48385. /**
  48386. * Sets the position the shadow will be casted from. Also use as the light position for both
  48387. * point and spot lights.
  48388. */
  48389. get: function () {
  48390. return this._position;
  48391. },
  48392. /**
  48393. * Sets the position the shadow will be casted from. Also use as the light position for both
  48394. * point and spot lights.
  48395. */
  48396. set: function (value) {
  48397. this._setPosition(value);
  48398. },
  48399. enumerable: true,
  48400. configurable: true
  48401. });
  48402. ShadowLight.prototype._setDirection = function (value) {
  48403. this._direction = value;
  48404. };
  48405. Object.defineProperty(ShadowLight.prototype, "direction", {
  48406. /**
  48407. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48408. * Also use as the light direction on spot and directional lights.
  48409. */
  48410. get: function () {
  48411. return this._direction;
  48412. },
  48413. /**
  48414. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48415. * Also use as the light direction on spot and directional lights.
  48416. */
  48417. set: function (value) {
  48418. this._setDirection(value);
  48419. },
  48420. enumerable: true,
  48421. configurable: true
  48422. });
  48423. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48424. /**
  48425. * Gets the shadow projection clipping minimum z value.
  48426. */
  48427. get: function () {
  48428. return this._shadowMinZ;
  48429. },
  48430. /**
  48431. * Sets the shadow projection clipping minimum z value.
  48432. */
  48433. set: function (value) {
  48434. this._shadowMinZ = value;
  48435. this.forceProjectionMatrixCompute();
  48436. },
  48437. enumerable: true,
  48438. configurable: true
  48439. });
  48440. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48441. /**
  48442. * Sets the shadow projection clipping maximum z value.
  48443. */
  48444. get: function () {
  48445. return this._shadowMaxZ;
  48446. },
  48447. /**
  48448. * Gets the shadow projection clipping maximum z value.
  48449. */
  48450. set: function (value) {
  48451. this._shadowMaxZ = value;
  48452. this.forceProjectionMatrixCompute();
  48453. },
  48454. enumerable: true,
  48455. configurable: true
  48456. });
  48457. /**
  48458. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48459. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48460. */
  48461. ShadowLight.prototype.computeTransformedInformation = function () {
  48462. if (this.parent && this.parent.getWorldMatrix) {
  48463. if (!this.transformedPosition) {
  48464. this.transformedPosition = BABYLON.Vector3.Zero();
  48465. }
  48466. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48467. // In case the direction is present.
  48468. if (this.direction) {
  48469. if (!this.transformedDirection) {
  48470. this.transformedDirection = BABYLON.Vector3.Zero();
  48471. }
  48472. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48473. }
  48474. return true;
  48475. }
  48476. return false;
  48477. };
  48478. /**
  48479. * Return the depth scale used for the shadow map.
  48480. * @returns the depth scale.
  48481. */
  48482. ShadowLight.prototype.getDepthScale = function () {
  48483. return 50.0;
  48484. };
  48485. /**
  48486. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48487. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48488. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48489. */
  48490. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48491. return this.transformedDirection ? this.transformedDirection : this.direction;
  48492. };
  48493. /**
  48494. * Returns the ShadowLight absolute position in the World.
  48495. * @returns the position vector in world space
  48496. */
  48497. ShadowLight.prototype.getAbsolutePosition = function () {
  48498. return this.transformedPosition ? this.transformedPosition : this.position;
  48499. };
  48500. /**
  48501. * Sets the ShadowLight direction toward the passed target.
  48502. * @param target The point tot target in local space
  48503. * @returns the updated ShadowLight direction
  48504. */
  48505. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48506. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48507. return this.direction;
  48508. };
  48509. /**
  48510. * Returns the light rotation in euler definition.
  48511. * @returns the x y z rotation in local space.
  48512. */
  48513. ShadowLight.prototype.getRotation = function () {
  48514. this.direction.normalize();
  48515. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48516. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48517. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48518. };
  48519. /**
  48520. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48521. * @returns true if a cube texture needs to be use
  48522. */
  48523. ShadowLight.prototype.needCube = function () {
  48524. return false;
  48525. };
  48526. /**
  48527. * Detects if the projection matrix requires to be recomputed this frame.
  48528. * @returns true if it requires to be recomputed otherwise, false.
  48529. */
  48530. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48531. return this._needProjectionMatrixCompute;
  48532. };
  48533. /**
  48534. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48535. */
  48536. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48537. this._needProjectionMatrixCompute = true;
  48538. };
  48539. /**
  48540. * Get the world matrix of the sahdow lights.
  48541. * @hidden Internal Use Only
  48542. */
  48543. ShadowLight.prototype._getWorldMatrix = function () {
  48544. if (!this._worldMatrix) {
  48545. this._worldMatrix = BABYLON.Matrix.Identity();
  48546. }
  48547. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48548. return this._worldMatrix;
  48549. };
  48550. /**
  48551. * Gets the minZ used for shadow according to both the scene and the light.
  48552. * @param activeCamera The camera we are returning the min for
  48553. * @returns the depth min z
  48554. */
  48555. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48556. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48557. };
  48558. /**
  48559. * Gets the maxZ used for shadow according to both the scene and the light.
  48560. * @param activeCamera The camera we are returning the max for
  48561. * @returns the depth max z
  48562. */
  48563. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48564. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48565. };
  48566. /**
  48567. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48568. * @param matrix The materix to updated with the projection information
  48569. * @param viewMatrix The transform matrix of the light
  48570. * @param renderList The list of mesh to render in the map
  48571. * @returns The current light
  48572. */
  48573. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48574. if (this.customProjectionMatrixBuilder) {
  48575. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48576. }
  48577. else {
  48578. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48579. }
  48580. return this;
  48581. };
  48582. __decorate([
  48583. BABYLON.serializeAsVector3()
  48584. ], ShadowLight.prototype, "position", null);
  48585. __decorate([
  48586. BABYLON.serializeAsVector3()
  48587. ], ShadowLight.prototype, "direction", null);
  48588. __decorate([
  48589. BABYLON.serialize()
  48590. ], ShadowLight.prototype, "shadowMinZ", null);
  48591. __decorate([
  48592. BABYLON.serialize()
  48593. ], ShadowLight.prototype, "shadowMaxZ", null);
  48594. return ShadowLight;
  48595. }(BABYLON.Light));
  48596. BABYLON.ShadowLight = ShadowLight;
  48597. })(BABYLON || (BABYLON = {}));
  48598. //# sourceMappingURL=babylon.shadowLight.js.map
  48599. var BABYLON;
  48600. (function (BABYLON) {
  48601. /**
  48602. * A point light is a light defined by an unique point in world space.
  48603. * The light is emitted in every direction from this point.
  48604. * A good example of a point light is a standard light bulb.
  48605. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48606. */
  48607. var PointLight = /** @class */ (function (_super) {
  48608. __extends(PointLight, _super);
  48609. /**
  48610. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48611. * A PointLight emits the light in every direction.
  48612. * It can cast shadows.
  48613. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48614. * ```javascript
  48615. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48616. * ```
  48617. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48618. * @param name The light friendly name
  48619. * @param position The position of the point light in the scene
  48620. * @param scene The scene the lights belongs to
  48621. */
  48622. function PointLight(name, position, scene) {
  48623. var _this = _super.call(this, name, scene) || this;
  48624. _this._shadowAngle = Math.PI / 2;
  48625. _this.position = position;
  48626. return _this;
  48627. }
  48628. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48629. /**
  48630. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48631. * This specifies what angle the shadow will use to be created.
  48632. *
  48633. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48634. */
  48635. get: function () {
  48636. return this._shadowAngle;
  48637. },
  48638. /**
  48639. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48640. * This specifies what angle the shadow will use to be created.
  48641. *
  48642. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48643. */
  48644. set: function (value) {
  48645. this._shadowAngle = value;
  48646. this.forceProjectionMatrixCompute();
  48647. },
  48648. enumerable: true,
  48649. configurable: true
  48650. });
  48651. Object.defineProperty(PointLight.prototype, "direction", {
  48652. /**
  48653. * Gets the direction if it has been set.
  48654. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48655. */
  48656. get: function () {
  48657. return this._direction;
  48658. },
  48659. /**
  48660. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48661. */
  48662. set: function (value) {
  48663. var previousNeedCube = this.needCube();
  48664. this._direction = value;
  48665. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48666. this._shadowGenerator.recreateShadowMap();
  48667. }
  48668. },
  48669. enumerable: true,
  48670. configurable: true
  48671. });
  48672. /**
  48673. * Returns the string "PointLight"
  48674. * @returns the class name
  48675. */
  48676. PointLight.prototype.getClassName = function () {
  48677. return "PointLight";
  48678. };
  48679. /**
  48680. * Returns the integer 0.
  48681. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48682. */
  48683. PointLight.prototype.getTypeID = function () {
  48684. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48685. };
  48686. /**
  48687. * Specifies wether or not the shadowmap should be a cube texture.
  48688. * @returns true if the shadowmap needs to be a cube texture.
  48689. */
  48690. PointLight.prototype.needCube = function () {
  48691. return !this.direction;
  48692. };
  48693. /**
  48694. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48695. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48696. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48697. */
  48698. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48699. if (this.direction) {
  48700. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48701. }
  48702. else {
  48703. switch (faceIndex) {
  48704. case 0:
  48705. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48706. case 1:
  48707. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48708. case 2:
  48709. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48710. case 3:
  48711. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48712. case 4:
  48713. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48714. case 5:
  48715. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48716. }
  48717. }
  48718. return BABYLON.Vector3.Zero();
  48719. };
  48720. /**
  48721. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48722. * - fov = PI / 2
  48723. * - aspect ratio : 1.0
  48724. * - z-near and far equal to the active camera minZ and maxZ.
  48725. * Returns the PointLight.
  48726. */
  48727. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48728. var activeCamera = this.getScene().activeCamera;
  48729. if (!activeCamera) {
  48730. return;
  48731. }
  48732. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48733. };
  48734. PointLight.prototype._buildUniformLayout = function () {
  48735. this._uniformBuffer.addUniform("vLightData", 4);
  48736. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48737. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48738. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48739. this._uniformBuffer.addUniform("depthValues", 2);
  48740. this._uniformBuffer.create();
  48741. };
  48742. /**
  48743. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48744. * @param effect The effect to update
  48745. * @param lightIndex The index of the light in the effect to update
  48746. * @returns The point light
  48747. */
  48748. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48749. if (this.computeTransformedInformation()) {
  48750. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48751. return this;
  48752. }
  48753. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48754. return this;
  48755. };
  48756. __decorate([
  48757. BABYLON.serialize()
  48758. ], PointLight.prototype, "shadowAngle", null);
  48759. return PointLight;
  48760. }(BABYLON.ShadowLight));
  48761. BABYLON.PointLight = PointLight;
  48762. })(BABYLON || (BABYLON = {}));
  48763. //# sourceMappingURL=babylon.pointLight.js.map
  48764. var BABYLON;
  48765. (function (BABYLON) {
  48766. /**
  48767. * A directional light is defined by a direction (what a surprise!).
  48768. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48769. * 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.
  48770. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48771. */
  48772. var DirectionalLight = /** @class */ (function (_super) {
  48773. __extends(DirectionalLight, _super);
  48774. /**
  48775. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48776. * The directional light is emitted from everywhere in the given direction.
  48777. * It can cast shawdows.
  48778. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48779. * @param name The friendly name of the light
  48780. * @param direction The direction of the light
  48781. * @param scene The scene the light belongs to
  48782. */
  48783. function DirectionalLight(name, direction, scene) {
  48784. var _this = _super.call(this, name, scene) || this;
  48785. _this._shadowFrustumSize = 0;
  48786. _this._shadowOrthoScale = 0.1;
  48787. /**
  48788. * Automatically compute the projection matrix to best fit (including all the casters)
  48789. * on each frame.
  48790. */
  48791. _this.autoUpdateExtends = true;
  48792. // Cache
  48793. _this._orthoLeft = Number.MAX_VALUE;
  48794. _this._orthoRight = Number.MIN_VALUE;
  48795. _this._orthoTop = Number.MIN_VALUE;
  48796. _this._orthoBottom = Number.MAX_VALUE;
  48797. _this.position = direction.scale(-1.0);
  48798. _this.direction = direction;
  48799. return _this;
  48800. }
  48801. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48802. /**
  48803. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48804. */
  48805. get: function () {
  48806. return this._shadowFrustumSize;
  48807. },
  48808. /**
  48809. * Specifies a fix frustum size for the shadow generation.
  48810. */
  48811. set: function (value) {
  48812. this._shadowFrustumSize = value;
  48813. this.forceProjectionMatrixCompute();
  48814. },
  48815. enumerable: true,
  48816. configurable: true
  48817. });
  48818. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48819. /**
  48820. * Gets the shadow projection scale against the optimal computed one.
  48821. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48822. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48823. */
  48824. get: function () {
  48825. return this._shadowOrthoScale;
  48826. },
  48827. /**
  48828. * Sets the shadow projection scale against the optimal computed one.
  48829. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48830. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48831. */
  48832. set: function (value) {
  48833. this._shadowOrthoScale = value;
  48834. this.forceProjectionMatrixCompute();
  48835. },
  48836. enumerable: true,
  48837. configurable: true
  48838. });
  48839. /**
  48840. * Returns the string "DirectionalLight".
  48841. * @return The class name
  48842. */
  48843. DirectionalLight.prototype.getClassName = function () {
  48844. return "DirectionalLight";
  48845. };
  48846. /**
  48847. * Returns the integer 1.
  48848. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48849. */
  48850. DirectionalLight.prototype.getTypeID = function () {
  48851. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48852. };
  48853. /**
  48854. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48855. * Returns the DirectionalLight Shadow projection matrix.
  48856. */
  48857. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48858. if (this.shadowFrustumSize > 0) {
  48859. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48860. }
  48861. else {
  48862. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48863. }
  48864. };
  48865. /**
  48866. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48867. * Returns the DirectionalLight Shadow projection matrix.
  48868. */
  48869. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48870. var activeCamera = this.getScene().activeCamera;
  48871. if (!activeCamera) {
  48872. return;
  48873. }
  48874. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48875. };
  48876. /**
  48877. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48878. * Returns the DirectionalLight Shadow projection matrix.
  48879. */
  48880. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48881. var activeCamera = this.getScene().activeCamera;
  48882. if (!activeCamera) {
  48883. return;
  48884. }
  48885. // Check extends
  48886. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48887. var tempVector3 = BABYLON.Vector3.Zero();
  48888. this._orthoLeft = Number.MAX_VALUE;
  48889. this._orthoRight = Number.MIN_VALUE;
  48890. this._orthoTop = Number.MIN_VALUE;
  48891. this._orthoBottom = Number.MAX_VALUE;
  48892. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48893. var mesh = renderList[meshIndex];
  48894. if (!mesh) {
  48895. continue;
  48896. }
  48897. var boundingInfo = mesh.getBoundingInfo();
  48898. var boundingBox = boundingInfo.boundingBox;
  48899. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48900. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48901. if (tempVector3.x < this._orthoLeft)
  48902. this._orthoLeft = tempVector3.x;
  48903. if (tempVector3.y < this._orthoBottom)
  48904. this._orthoBottom = tempVector3.y;
  48905. if (tempVector3.x > this._orthoRight)
  48906. this._orthoRight = tempVector3.x;
  48907. if (tempVector3.y > this._orthoTop)
  48908. this._orthoTop = tempVector3.y;
  48909. }
  48910. }
  48911. }
  48912. var xOffset = this._orthoRight - this._orthoLeft;
  48913. var yOffset = this._orthoTop - this._orthoBottom;
  48914. 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);
  48915. };
  48916. DirectionalLight.prototype._buildUniformLayout = function () {
  48917. this._uniformBuffer.addUniform("vLightData", 4);
  48918. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48919. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48920. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48921. this._uniformBuffer.addUniform("depthValues", 2);
  48922. this._uniformBuffer.create();
  48923. };
  48924. /**
  48925. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48926. * @param effect The effect to update
  48927. * @param lightIndex The index of the light in the effect to update
  48928. * @returns The directional light
  48929. */
  48930. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48931. if (this.computeTransformedInformation()) {
  48932. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48933. return this;
  48934. }
  48935. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48936. return this;
  48937. };
  48938. /**
  48939. * Gets the minZ used for shadow according to both the scene and the light.
  48940. *
  48941. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48942. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48943. * @param activeCamera The camera we are returning the min for
  48944. * @returns the depth min z
  48945. */
  48946. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48947. return 1;
  48948. };
  48949. /**
  48950. * Gets the maxZ used for shadow according to both the scene and the light.
  48951. *
  48952. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48953. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48954. * @param activeCamera The camera we are returning the max for
  48955. * @returns the depth max z
  48956. */
  48957. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48958. return 1;
  48959. };
  48960. __decorate([
  48961. BABYLON.serialize()
  48962. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48963. __decorate([
  48964. BABYLON.serialize()
  48965. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48966. __decorate([
  48967. BABYLON.serialize()
  48968. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48969. return DirectionalLight;
  48970. }(BABYLON.ShadowLight));
  48971. BABYLON.DirectionalLight = DirectionalLight;
  48972. })(BABYLON || (BABYLON = {}));
  48973. //# sourceMappingURL=babylon.directionalLight.js.map
  48974. var BABYLON;
  48975. (function (BABYLON) {
  48976. /**
  48977. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48978. * These values define a cone of light starting from the position, emitting toward the direction.
  48979. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48980. * and the exponent defines the speed of the decay of the light with distance (reach).
  48981. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48982. */
  48983. var SpotLight = /** @class */ (function (_super) {
  48984. __extends(SpotLight, _super);
  48985. /**
  48986. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48987. * It can cast shadows.
  48988. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48989. * @param name The light friendly name
  48990. * @param position The position of the spot light in the scene
  48991. * @param direction The direction of the light in the scene
  48992. * @param angle The cone angle of the light in Radians
  48993. * @param exponent The light decay speed with the distance from the emission spot
  48994. * @param scene The scene the lights belongs to
  48995. */
  48996. function SpotLight(name, position, direction, angle, exponent, scene) {
  48997. var _this = _super.call(this, name, scene) || this;
  48998. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48999. _this._projectionTextureLightNear = 1e-6;
  49000. _this._projectionTextureLightFar = 1000.0;
  49001. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49002. _this._projectionTextureViewLightDirty = true;
  49003. _this._projectionTextureProjectionLightDirty = true;
  49004. _this._projectionTextureDirty = true;
  49005. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49006. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49007. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49008. _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);
  49009. _this.position = position;
  49010. _this.direction = direction;
  49011. _this.angle = angle;
  49012. _this.exponent = exponent;
  49013. return _this;
  49014. }
  49015. Object.defineProperty(SpotLight.prototype, "angle", {
  49016. /**
  49017. * Gets the cone angle of the spot light in Radians.
  49018. */
  49019. get: function () {
  49020. return this._angle;
  49021. },
  49022. /**
  49023. * Sets the cone angle of the spot light in Radians.
  49024. */
  49025. set: function (value) {
  49026. this._angle = value;
  49027. this._projectionTextureProjectionLightDirty = true;
  49028. this.forceProjectionMatrixCompute();
  49029. },
  49030. enumerable: true,
  49031. configurable: true
  49032. });
  49033. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49034. /**
  49035. * Allows scaling the angle of the light for shadow generation only.
  49036. */
  49037. get: function () {
  49038. return this._shadowAngleScale;
  49039. },
  49040. /**
  49041. * Allows scaling the angle of the light for shadow generation only.
  49042. */
  49043. set: function (value) {
  49044. this._shadowAngleScale = value;
  49045. this.forceProjectionMatrixCompute();
  49046. },
  49047. enumerable: true,
  49048. configurable: true
  49049. });
  49050. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49051. /**
  49052. * Allows reading the projecton texture
  49053. */
  49054. get: function () {
  49055. return this._projectionTextureMatrix;
  49056. },
  49057. enumerable: true,
  49058. configurable: true
  49059. });
  49060. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49061. /**
  49062. * Gets the near clip of the Spotlight for texture projection.
  49063. */
  49064. get: function () {
  49065. return this._projectionTextureLightNear;
  49066. },
  49067. /**
  49068. * Sets the near clip of the Spotlight for texture projection.
  49069. */
  49070. set: function (value) {
  49071. this._projectionTextureLightNear = value;
  49072. this._projectionTextureProjectionLightDirty = true;
  49073. },
  49074. enumerable: true,
  49075. configurable: true
  49076. });
  49077. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49078. /**
  49079. * Gets the far clip of the Spotlight for texture projection.
  49080. */
  49081. get: function () {
  49082. return this._projectionTextureLightFar;
  49083. },
  49084. /**
  49085. * Sets the far clip of the Spotlight for texture projection.
  49086. */
  49087. set: function (value) {
  49088. this._projectionTextureLightFar = value;
  49089. this._projectionTextureProjectionLightDirty = true;
  49090. },
  49091. enumerable: true,
  49092. configurable: true
  49093. });
  49094. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49095. /**
  49096. * Gets the Up vector of the Spotlight for texture projection.
  49097. */
  49098. get: function () {
  49099. return this._projectionTextureUpDirection;
  49100. },
  49101. /**
  49102. * Sets the Up vector of the Spotlight for texture projection.
  49103. */
  49104. set: function (value) {
  49105. this._projectionTextureUpDirection = value;
  49106. this._projectionTextureProjectionLightDirty = true;
  49107. },
  49108. enumerable: true,
  49109. configurable: true
  49110. });
  49111. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49112. /**
  49113. * Gets the projection texture of the light.
  49114. */
  49115. get: function () {
  49116. return this._projectionTexture;
  49117. },
  49118. /**
  49119. * Sets the projection texture of the light.
  49120. */
  49121. set: function (value) {
  49122. this._projectionTexture = value;
  49123. this._projectionTextureDirty = true;
  49124. },
  49125. enumerable: true,
  49126. configurable: true
  49127. });
  49128. /**
  49129. * Returns the string "SpotLight".
  49130. * @returns the class name
  49131. */
  49132. SpotLight.prototype.getClassName = function () {
  49133. return "SpotLight";
  49134. };
  49135. /**
  49136. * Returns the integer 2.
  49137. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49138. */
  49139. SpotLight.prototype.getTypeID = function () {
  49140. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49141. };
  49142. /**
  49143. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49144. */
  49145. SpotLight.prototype._setDirection = function (value) {
  49146. _super.prototype._setDirection.call(this, value);
  49147. this._projectionTextureViewLightDirty = true;
  49148. };
  49149. /**
  49150. * Overrides the position setter to recompute the projection texture view light Matrix.
  49151. */
  49152. SpotLight.prototype._setPosition = function (value) {
  49153. _super.prototype._setPosition.call(this, value);
  49154. this._projectionTextureViewLightDirty = true;
  49155. };
  49156. /**
  49157. * 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.
  49158. * Returns the SpotLight.
  49159. */
  49160. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49161. var activeCamera = this.getScene().activeCamera;
  49162. if (!activeCamera) {
  49163. return;
  49164. }
  49165. this._shadowAngleScale = this._shadowAngleScale || 1;
  49166. var angle = this._shadowAngleScale * this._angle;
  49167. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49168. };
  49169. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49170. this._projectionTextureViewLightDirty = false;
  49171. this._projectionTextureDirty = true;
  49172. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49173. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49174. };
  49175. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49176. this._projectionTextureProjectionLightDirty = false;
  49177. this._projectionTextureDirty = true;
  49178. var light_far = this.projectionTextureLightFar;
  49179. var light_near = this.projectionTextureLightNear;
  49180. var P = light_far / (light_far - light_near);
  49181. var Q = -P * light_near;
  49182. var S = 1.0 / Math.tan(this._angle / 2.0);
  49183. var A = 1.0;
  49184. 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);
  49185. };
  49186. /**
  49187. * Main function for light texture projection matrix computing.
  49188. */
  49189. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49190. this._projectionTextureDirty = false;
  49191. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49192. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49193. };
  49194. SpotLight.prototype._buildUniformLayout = function () {
  49195. this._uniformBuffer.addUniform("vLightData", 4);
  49196. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49197. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49198. this._uniformBuffer.addUniform("vLightDirection", 3);
  49199. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49200. this._uniformBuffer.addUniform("depthValues", 2);
  49201. this._uniformBuffer.create();
  49202. };
  49203. /**
  49204. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49205. * @param effect The effect to update
  49206. * @param lightIndex The index of the light in the effect to update
  49207. * @returns The spot light
  49208. */
  49209. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49210. var normalizeDirection;
  49211. if (this.computeTransformedInformation()) {
  49212. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49213. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49214. }
  49215. else {
  49216. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49217. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49218. }
  49219. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49220. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49221. if (this._projectionTextureViewLightDirty) {
  49222. this._computeProjectionTextureViewLightMatrix();
  49223. }
  49224. if (this._projectionTextureProjectionLightDirty) {
  49225. this._computeProjectionTextureProjectionLightMatrix();
  49226. }
  49227. if (this._projectionTextureDirty) {
  49228. this._computeProjectionTextureMatrix();
  49229. }
  49230. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49231. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49232. }
  49233. return this;
  49234. };
  49235. /**
  49236. * Disposes the light and the associated resources.
  49237. */
  49238. SpotLight.prototype.dispose = function () {
  49239. _super.prototype.dispose.call(this);
  49240. if (this._projectionTexture) {
  49241. this._projectionTexture.dispose();
  49242. }
  49243. };
  49244. __decorate([
  49245. BABYLON.serialize()
  49246. ], SpotLight.prototype, "angle", null);
  49247. __decorate([
  49248. BABYLON.serialize()
  49249. ], SpotLight.prototype, "shadowAngleScale", null);
  49250. __decorate([
  49251. BABYLON.serialize()
  49252. ], SpotLight.prototype, "exponent", void 0);
  49253. __decorate([
  49254. BABYLON.serialize()
  49255. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49256. __decorate([
  49257. BABYLON.serialize()
  49258. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49259. __decorate([
  49260. BABYLON.serialize()
  49261. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49262. __decorate([
  49263. BABYLON.serializeAsTexture("projectedLightTexture")
  49264. ], SpotLight.prototype, "_projectionTexture", void 0);
  49265. return SpotLight;
  49266. }(BABYLON.ShadowLight));
  49267. BABYLON.SpotLight = SpotLight;
  49268. })(BABYLON || (BABYLON = {}));
  49269. //# sourceMappingURL=babylon.spotLight.js.map
  49270. var BABYLON;
  49271. (function (BABYLON) {
  49272. /**
  49273. * Class used to override all child animations of a given target
  49274. */
  49275. var AnimationPropertiesOverride = /** @class */ (function () {
  49276. function AnimationPropertiesOverride() {
  49277. /**
  49278. * Gets or sets a value indicating if animation blending must be used
  49279. */
  49280. this.enableBlending = false;
  49281. /**
  49282. * Gets or sets the blending speed to use when enableBlending is true
  49283. */
  49284. this.blendingSpeed = 0.01;
  49285. /**
  49286. * Gets or sets the default loop mode to use
  49287. */
  49288. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49289. }
  49290. return AnimationPropertiesOverride;
  49291. }());
  49292. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49293. })(BABYLON || (BABYLON = {}));
  49294. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49295. var BABYLON;
  49296. (function (BABYLON) {
  49297. /**
  49298. * Represents the range of an animation
  49299. */
  49300. var AnimationRange = /** @class */ (function () {
  49301. /**
  49302. * Initializes the range of an animation
  49303. * @param name The name of the animation range
  49304. * @param from The starting frame of the animation
  49305. * @param to The ending frame of the animation
  49306. */
  49307. function AnimationRange(
  49308. /**The name of the animation range**/
  49309. name,
  49310. /**The starting frame of the animation */
  49311. from,
  49312. /**The ending frame of the animation*/
  49313. to) {
  49314. this.name = name;
  49315. this.from = from;
  49316. this.to = to;
  49317. }
  49318. /**
  49319. * Makes a copy of the animation range
  49320. * @returns A copy of the animation range
  49321. */
  49322. AnimationRange.prototype.clone = function () {
  49323. return new AnimationRange(this.name, this.from, this.to);
  49324. };
  49325. return AnimationRange;
  49326. }());
  49327. BABYLON.AnimationRange = AnimationRange;
  49328. /**
  49329. * Composed of a frame, and an action function
  49330. */
  49331. var AnimationEvent = /** @class */ (function () {
  49332. /**
  49333. * Initializes the animation event
  49334. * @param frame The frame for which the event is triggered
  49335. * @param action The event to perform when triggered
  49336. * @param onlyOnce Specifies if the event should be triggered only once
  49337. */
  49338. function AnimationEvent(
  49339. /** The frame for which the event is triggered **/
  49340. frame,
  49341. /** The event to perform when triggered **/
  49342. action,
  49343. /** Specifies if the event should be triggered only once**/
  49344. onlyOnce) {
  49345. this.frame = frame;
  49346. this.action = action;
  49347. this.onlyOnce = onlyOnce;
  49348. /**
  49349. * Specifies if the animation event is done
  49350. */
  49351. this.isDone = false;
  49352. }
  49353. /** @hidden */
  49354. AnimationEvent.prototype._clone = function () {
  49355. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49356. };
  49357. return AnimationEvent;
  49358. }());
  49359. BABYLON.AnimationEvent = AnimationEvent;
  49360. /**
  49361. * A cursor which tracks a point on a path
  49362. */
  49363. var PathCursor = /** @class */ (function () {
  49364. /**
  49365. * Initializes the path cursor
  49366. * @param path The path to track
  49367. */
  49368. function PathCursor(path) {
  49369. this.path = path;
  49370. /**
  49371. * Stores path cursor callbacks for when an onchange event is triggered
  49372. */
  49373. this._onchange = new Array();
  49374. /**
  49375. * The value of the path cursor
  49376. */
  49377. this.value = 0;
  49378. /**
  49379. * The animation array of the path cursor
  49380. */
  49381. this.animations = new Array();
  49382. }
  49383. /**
  49384. * Gets the cursor point on the path
  49385. * @returns A point on the path cursor at the cursor location
  49386. */
  49387. PathCursor.prototype.getPoint = function () {
  49388. var point = this.path.getPointAtLengthPosition(this.value);
  49389. return new BABYLON.Vector3(point.x, 0, point.y);
  49390. };
  49391. /**
  49392. * Moves the cursor ahead by the step amount
  49393. * @param step The amount to move the cursor forward
  49394. * @returns This path cursor
  49395. */
  49396. PathCursor.prototype.moveAhead = function (step) {
  49397. if (step === void 0) { step = 0.002; }
  49398. this.move(step);
  49399. return this;
  49400. };
  49401. /**
  49402. * Moves the cursor behind by the step amount
  49403. * @param step The amount to move the cursor back
  49404. * @returns This path cursor
  49405. */
  49406. PathCursor.prototype.moveBack = function (step) {
  49407. if (step === void 0) { step = 0.002; }
  49408. this.move(-step);
  49409. return this;
  49410. };
  49411. /**
  49412. * Moves the cursor by the step amount
  49413. * If the step amount is greater than one, an exception is thrown
  49414. * @param step The amount to move the cursor
  49415. * @returns This path cursor
  49416. */
  49417. PathCursor.prototype.move = function (step) {
  49418. if (Math.abs(step) > 1) {
  49419. throw "step size should be less than 1.";
  49420. }
  49421. this.value += step;
  49422. this.ensureLimits();
  49423. this.raiseOnChange();
  49424. return this;
  49425. };
  49426. /**
  49427. * Ensures that the value is limited between zero and one
  49428. * @returns This path cursor
  49429. */
  49430. PathCursor.prototype.ensureLimits = function () {
  49431. while (this.value > 1) {
  49432. this.value -= 1;
  49433. }
  49434. while (this.value < 0) {
  49435. this.value += 1;
  49436. }
  49437. return this;
  49438. };
  49439. /**
  49440. * Runs onchange callbacks on change (used by the animation engine)
  49441. * @returns This path cursor
  49442. */
  49443. PathCursor.prototype.raiseOnChange = function () {
  49444. var _this = this;
  49445. this._onchange.forEach(function (f) { return f(_this); });
  49446. return this;
  49447. };
  49448. /**
  49449. * Executes a function on change
  49450. * @param f A path cursor onchange callback
  49451. * @returns This path cursor
  49452. */
  49453. PathCursor.prototype.onchange = function (f) {
  49454. this._onchange.push(f);
  49455. return this;
  49456. };
  49457. return PathCursor;
  49458. }());
  49459. BABYLON.PathCursor = PathCursor;
  49460. /**
  49461. * Enum for the animation key frame interpolation type
  49462. */
  49463. var AnimationKeyInterpolation;
  49464. (function (AnimationKeyInterpolation) {
  49465. /**
  49466. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49467. */
  49468. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49469. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49470. /**
  49471. * Class used to store any kind of animation
  49472. */
  49473. var Animation = /** @class */ (function () {
  49474. /**
  49475. * Initializes the animation
  49476. * @param name Name of the animation
  49477. * @param targetProperty Property to animate
  49478. * @param framePerSecond The frames per second of the animation
  49479. * @param dataType The data type of the animation
  49480. * @param loopMode The loop mode of the animation
  49481. * @param enableBlendings Specifies if blending should be enabled
  49482. */
  49483. function Animation(
  49484. /**Name of the animation */
  49485. name,
  49486. /**Property to animate */
  49487. targetProperty,
  49488. /**The frames per second of the animation */
  49489. framePerSecond,
  49490. /**The data type of the animation */
  49491. dataType,
  49492. /**The loop mode of the animation */
  49493. loopMode,
  49494. /**Specifies if blending should be enabled */
  49495. enableBlending) {
  49496. this.name = name;
  49497. this.targetProperty = targetProperty;
  49498. this.framePerSecond = framePerSecond;
  49499. this.dataType = dataType;
  49500. this.loopMode = loopMode;
  49501. this.enableBlending = enableBlending;
  49502. /**
  49503. * @hidden Internal use only
  49504. */
  49505. this._runtimeAnimations = new Array();
  49506. /**
  49507. * The set of event that will be linked to this animation
  49508. */
  49509. this._events = new Array();
  49510. /**
  49511. * Stores the blending speed of the animation
  49512. */
  49513. this.blendingSpeed = 0.01;
  49514. /**
  49515. * Stores the animation ranges for the animation
  49516. */
  49517. this._ranges = {};
  49518. this.targetPropertyPath = targetProperty.split(".");
  49519. this.dataType = dataType;
  49520. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49521. }
  49522. /**
  49523. * @hidden Internal use
  49524. */
  49525. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49526. var dataType = undefined;
  49527. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49528. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49529. }
  49530. else if (from instanceof BABYLON.Quaternion) {
  49531. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49532. }
  49533. else if (from instanceof BABYLON.Vector3) {
  49534. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49535. }
  49536. else if (from instanceof BABYLON.Vector2) {
  49537. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49538. }
  49539. else if (from instanceof BABYLON.Color3) {
  49540. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49541. }
  49542. else if (from instanceof BABYLON.Size) {
  49543. dataType = Animation.ANIMATIONTYPE_SIZE;
  49544. }
  49545. if (dataType == undefined) {
  49546. return null;
  49547. }
  49548. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49549. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49550. animation.setKeys(keys);
  49551. if (easingFunction !== undefined) {
  49552. animation.setEasingFunction(easingFunction);
  49553. }
  49554. return animation;
  49555. };
  49556. /**
  49557. * Sets up an animation
  49558. * @param property The property to animate
  49559. * @param animationType The animation type to apply
  49560. * @param framePerSecond The frames per second of the animation
  49561. * @param easingFunction The easing function used in the animation
  49562. * @returns The created animation
  49563. */
  49564. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49565. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49566. animation.setEasingFunction(easingFunction);
  49567. return animation;
  49568. };
  49569. /**
  49570. * Create and start an animation on a node
  49571. * @param name defines the name of the global animation that will be run on all nodes
  49572. * @param node defines the root node where the animation will take place
  49573. * @param targetProperty defines property to animate
  49574. * @param framePerSecond defines the number of frame per second yo use
  49575. * @param totalFrame defines the number of frames in total
  49576. * @param from defines the initial value
  49577. * @param to defines the final value
  49578. * @param loopMode defines which loop mode you want to use (off by default)
  49579. * @param easingFunction defines the easing function to use (linear by default)
  49580. * @param onAnimationEnd defines the callback to call when animation end
  49581. * @returns the animatable created for this animation
  49582. */
  49583. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49584. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49585. if (!animation) {
  49586. return null;
  49587. }
  49588. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49589. };
  49590. /**
  49591. * Create and start an animation on a node and its descendants
  49592. * @param name defines the name of the global animation that will be run on all nodes
  49593. * @param node defines the root node where the animation will take place
  49594. * @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
  49595. * @param targetProperty defines property to animate
  49596. * @param framePerSecond defines the number of frame per second to use
  49597. * @param totalFrame defines the number of frames in total
  49598. * @param from defines the initial value
  49599. * @param to defines the final value
  49600. * @param loopMode defines which loop mode you want to use (off by default)
  49601. * @param easingFunction defines the easing function to use (linear by default)
  49602. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49603. * @returns the list of animatables created for all nodes
  49604. * @example https://www.babylonjs-playground.com/#MH0VLI
  49605. */
  49606. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49607. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49608. if (!animation) {
  49609. return null;
  49610. }
  49611. var scene = node.getScene();
  49612. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49613. };
  49614. /**
  49615. * Creates a new animation, merges it with the existing animations and starts it
  49616. * @param name Name of the animation
  49617. * @param node Node which contains the scene that begins the animations
  49618. * @param targetProperty Specifies which property to animate
  49619. * @param framePerSecond The frames per second of the animation
  49620. * @param totalFrame The total number of frames
  49621. * @param from The frame at the beginning of the animation
  49622. * @param to The frame at the end of the animation
  49623. * @param loopMode Specifies the loop mode of the animation
  49624. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49625. * @param onAnimationEnd Callback to run once the animation is complete
  49626. * @returns Nullable animation
  49627. */
  49628. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49629. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49630. if (!animation) {
  49631. return null;
  49632. }
  49633. node.animations.push(animation);
  49634. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49635. };
  49636. /**
  49637. * Transition property of an host to the target Value
  49638. * @param property The property to transition
  49639. * @param targetValue The target Value of the property
  49640. * @param host The object where the property to animate belongs
  49641. * @param scene Scene used to run the animation
  49642. * @param frameRate Framerate (in frame/s) to use
  49643. * @param transition The transition type we want to use
  49644. * @param duration The duration of the animation, in milliseconds
  49645. * @param onAnimationEnd Callback trigger at the end of the animation
  49646. * @returns Nullable animation
  49647. */
  49648. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49649. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49650. if (duration <= 0) {
  49651. host[property] = targetValue;
  49652. if (onAnimationEnd) {
  49653. onAnimationEnd();
  49654. }
  49655. return null;
  49656. }
  49657. var endFrame = frameRate * (duration / 1000);
  49658. transition.setKeys([{
  49659. frame: 0,
  49660. value: host[property].clone ? host[property].clone() : host[property]
  49661. },
  49662. {
  49663. frame: endFrame,
  49664. value: targetValue
  49665. }]);
  49666. if (!host.animations) {
  49667. host.animations = [];
  49668. }
  49669. host.animations.push(transition);
  49670. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49671. animation.onAnimationEnd = onAnimationEnd;
  49672. return animation;
  49673. };
  49674. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49675. /**
  49676. * Return the array of runtime animations currently using this animation
  49677. */
  49678. get: function () {
  49679. return this._runtimeAnimations;
  49680. },
  49681. enumerable: true,
  49682. configurable: true
  49683. });
  49684. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49685. /**
  49686. * Specifies if any of the runtime animations are currently running
  49687. */
  49688. get: function () {
  49689. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49690. var runtimeAnimation = _a[_i];
  49691. if (!runtimeAnimation.isStopped) {
  49692. return true;
  49693. }
  49694. }
  49695. return false;
  49696. },
  49697. enumerable: true,
  49698. configurable: true
  49699. });
  49700. // Methods
  49701. /**
  49702. * Converts the animation to a string
  49703. * @param fullDetails support for multiple levels of logging within scene loading
  49704. * @returns String form of the animation
  49705. */
  49706. Animation.prototype.toString = function (fullDetails) {
  49707. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49708. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49709. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49710. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49711. if (fullDetails) {
  49712. ret += ", Ranges: {";
  49713. var first = true;
  49714. for (var name in this._ranges) {
  49715. if (first) {
  49716. ret += ", ";
  49717. first = false;
  49718. }
  49719. ret += name;
  49720. }
  49721. ret += "}";
  49722. }
  49723. return ret;
  49724. };
  49725. /**
  49726. * Add an event to this animation
  49727. * @param event Event to add
  49728. */
  49729. Animation.prototype.addEvent = function (event) {
  49730. this._events.push(event);
  49731. };
  49732. /**
  49733. * Remove all events found at the given frame
  49734. * @param frame The frame to remove events from
  49735. */
  49736. Animation.prototype.removeEvents = function (frame) {
  49737. for (var index = 0; index < this._events.length; index++) {
  49738. if (this._events[index].frame === frame) {
  49739. this._events.splice(index, 1);
  49740. index--;
  49741. }
  49742. }
  49743. };
  49744. /**
  49745. * Retrieves all the events from the animation
  49746. * @returns Events from the animation
  49747. */
  49748. Animation.prototype.getEvents = function () {
  49749. return this._events;
  49750. };
  49751. /**
  49752. * Creates an animation range
  49753. * @param name Name of the animation range
  49754. * @param from Starting frame of the animation range
  49755. * @param to Ending frame of the animation
  49756. */
  49757. Animation.prototype.createRange = function (name, from, to) {
  49758. // check name not already in use; could happen for bones after serialized
  49759. if (!this._ranges[name]) {
  49760. this._ranges[name] = new AnimationRange(name, from, to);
  49761. }
  49762. };
  49763. /**
  49764. * Deletes an animation range by name
  49765. * @param name Name of the animation range to delete
  49766. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49767. */
  49768. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49769. if (deleteFrames === void 0) { deleteFrames = true; }
  49770. var range = this._ranges[name];
  49771. if (!range) {
  49772. return;
  49773. }
  49774. if (deleteFrames) {
  49775. var from = range.from;
  49776. var to = range.to;
  49777. // this loop MUST go high to low for multiple splices to work
  49778. for (var key = this._keys.length - 1; key >= 0; key--) {
  49779. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49780. this._keys.splice(key, 1);
  49781. }
  49782. }
  49783. }
  49784. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49785. };
  49786. /**
  49787. * Gets the animation range by name, or null if not defined
  49788. * @param name Name of the animation range
  49789. * @returns Nullable animation range
  49790. */
  49791. Animation.prototype.getRange = function (name) {
  49792. return this._ranges[name];
  49793. };
  49794. /**
  49795. * Gets the key frames from the animation
  49796. * @returns The key frames of the animation
  49797. */
  49798. Animation.prototype.getKeys = function () {
  49799. return this._keys;
  49800. };
  49801. /**
  49802. * Gets the highest frame rate of the animation
  49803. * @returns Highest frame rate of the animation
  49804. */
  49805. Animation.prototype.getHighestFrame = function () {
  49806. var ret = 0;
  49807. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49808. if (ret < this._keys[key].frame) {
  49809. ret = this._keys[key].frame;
  49810. }
  49811. }
  49812. return ret;
  49813. };
  49814. /**
  49815. * Gets the easing function of the animation
  49816. * @returns Easing function of the animation
  49817. */
  49818. Animation.prototype.getEasingFunction = function () {
  49819. return this._easingFunction;
  49820. };
  49821. /**
  49822. * Sets the easing function of the animation
  49823. * @param easingFunction A custom mathematical formula for animation
  49824. */
  49825. Animation.prototype.setEasingFunction = function (easingFunction) {
  49826. this._easingFunction = easingFunction;
  49827. };
  49828. /**
  49829. * Interpolates a scalar linearly
  49830. * @param startValue Start value of the animation curve
  49831. * @param endValue End value of the animation curve
  49832. * @param gradient Scalar amount to interpolate
  49833. * @returns Interpolated scalar value
  49834. */
  49835. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49836. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49837. };
  49838. /**
  49839. * Interpolates a scalar cubically
  49840. * @param startValue Start value of the animation curve
  49841. * @param outTangent End tangent of the animation
  49842. * @param endValue End value of the animation curve
  49843. * @param inTangent Start tangent of the animation curve
  49844. * @param gradient Scalar amount to interpolate
  49845. * @returns Interpolated scalar value
  49846. */
  49847. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49848. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49849. };
  49850. /**
  49851. * Interpolates a quaternion using a spherical linear interpolation
  49852. * @param startValue Start value of the animation curve
  49853. * @param endValue End value of the animation curve
  49854. * @param gradient Scalar amount to interpolate
  49855. * @returns Interpolated quaternion value
  49856. */
  49857. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49858. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49859. };
  49860. /**
  49861. * Interpolates a quaternion cubically
  49862. * @param startValue Start value of the animation curve
  49863. * @param outTangent End tangent of the animation curve
  49864. * @param endValue End value of the animation curve
  49865. * @param inTangent Start tangent of the animation curve
  49866. * @param gradient Scalar amount to interpolate
  49867. * @returns Interpolated quaternion value
  49868. */
  49869. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49870. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49871. };
  49872. /**
  49873. * Interpolates a Vector3 linearl
  49874. * @param startValue Start value of the animation curve
  49875. * @param endValue End value of the animation curve
  49876. * @param gradient Scalar amount to interpolate
  49877. * @returns Interpolated scalar value
  49878. */
  49879. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49880. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49881. };
  49882. /**
  49883. * Interpolates a Vector3 cubically
  49884. * @param startValue Start value of the animation curve
  49885. * @param outTangent End tangent of the animation
  49886. * @param endValue End value of the animation curve
  49887. * @param inTangent Start tangent of the animation curve
  49888. * @param gradient Scalar amount to interpolate
  49889. * @returns InterpolatedVector3 value
  49890. */
  49891. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49892. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49893. };
  49894. /**
  49895. * Interpolates a Vector2 linearly
  49896. * @param startValue Start value of the animation curve
  49897. * @param endValue End value of the animation curve
  49898. * @param gradient Scalar amount to interpolate
  49899. * @returns Interpolated Vector2 value
  49900. */
  49901. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49902. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49903. };
  49904. /**
  49905. * Interpolates a Vector2 cubically
  49906. * @param startValue Start value of the animation curve
  49907. * @param outTangent End tangent of the animation
  49908. * @param endValue End value of the animation curve
  49909. * @param inTangent Start tangent of the animation curve
  49910. * @param gradient Scalar amount to interpolate
  49911. * @returns Interpolated Vector2 value
  49912. */
  49913. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49914. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49915. };
  49916. /**
  49917. * Interpolates a size linearly
  49918. * @param startValue Start value of the animation curve
  49919. * @param endValue End value of the animation curve
  49920. * @param gradient Scalar amount to interpolate
  49921. * @returns Interpolated Size value
  49922. */
  49923. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49924. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49925. };
  49926. /**
  49927. * Interpolates a Color3 linearly
  49928. * @param startValue Start value of the animation curve
  49929. * @param endValue End value of the animation curve
  49930. * @param gradient Scalar amount to interpolate
  49931. * @returns Interpolated Color3 value
  49932. */
  49933. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49934. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49935. };
  49936. /**
  49937. * @hidden Internal use only
  49938. */
  49939. Animation.prototype._getKeyValue = function (value) {
  49940. if (typeof value === "function") {
  49941. return value();
  49942. }
  49943. return value;
  49944. };
  49945. /**
  49946. * @hidden Internal use only
  49947. */
  49948. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49949. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49950. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49951. }
  49952. var keys = this.getKeys();
  49953. // Try to get a hash to find the right key
  49954. 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));
  49955. if (keys[startKeyIndex].frame >= currentFrame) {
  49956. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49957. startKeyIndex--;
  49958. }
  49959. }
  49960. for (var key = startKeyIndex; key < keys.length; key++) {
  49961. var endKey = keys[key + 1];
  49962. if (endKey.frame >= currentFrame) {
  49963. var startKey = keys[key];
  49964. var startValue = this._getKeyValue(startKey.value);
  49965. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49966. return startValue;
  49967. }
  49968. var endValue = this._getKeyValue(endKey.value);
  49969. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49970. var frameDelta = endKey.frame - startKey.frame;
  49971. // gradient : percent of currentFrame between the frame inf and the frame sup
  49972. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49973. // check for easingFunction and correction of gradient
  49974. var easingFunction = this.getEasingFunction();
  49975. if (easingFunction != null) {
  49976. gradient = easingFunction.ease(gradient);
  49977. }
  49978. switch (this.dataType) {
  49979. // Float
  49980. case Animation.ANIMATIONTYPE_FLOAT:
  49981. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49982. switch (loopMode) {
  49983. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49984. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49985. return floatValue;
  49986. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49987. return offsetValue * repeatCount + floatValue;
  49988. }
  49989. break;
  49990. // Quaternion
  49991. case Animation.ANIMATIONTYPE_QUATERNION:
  49992. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49993. switch (loopMode) {
  49994. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49995. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49996. return quatValue;
  49997. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49998. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49999. }
  50000. return quatValue;
  50001. // Vector3
  50002. case Animation.ANIMATIONTYPE_VECTOR3:
  50003. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50004. switch (loopMode) {
  50005. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50006. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50007. return vec3Value;
  50008. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50009. return vec3Value.add(offsetValue.scale(repeatCount));
  50010. }
  50011. // Vector2
  50012. case Animation.ANIMATIONTYPE_VECTOR2:
  50013. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50014. switch (loopMode) {
  50015. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50016. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50017. return vec2Value;
  50018. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50019. return vec2Value.add(offsetValue.scale(repeatCount));
  50020. }
  50021. // Size
  50022. case Animation.ANIMATIONTYPE_SIZE:
  50023. switch (loopMode) {
  50024. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50025. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50026. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50027. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50028. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50029. }
  50030. // Color3
  50031. case Animation.ANIMATIONTYPE_COLOR3:
  50032. switch (loopMode) {
  50033. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50034. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50035. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50036. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50037. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50038. }
  50039. // Matrix
  50040. case Animation.ANIMATIONTYPE_MATRIX:
  50041. switch (loopMode) {
  50042. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50043. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50044. if (Animation.AllowMatricesInterpolation) {
  50045. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50046. }
  50047. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50048. return startValue;
  50049. }
  50050. default:
  50051. break;
  50052. }
  50053. break;
  50054. }
  50055. }
  50056. return this._getKeyValue(keys[keys.length - 1].value);
  50057. };
  50058. /**
  50059. * Defines the function to use to interpolate matrices
  50060. * @param startValue defines the start matrix
  50061. * @param endValue defines the end matrix
  50062. * @param gradient defines the gradient between both matrices
  50063. * @param result defines an optional target matrix where to store the interpolation
  50064. * @returns the interpolated matrix
  50065. */
  50066. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50067. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50068. if (result) {
  50069. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50070. return result;
  50071. }
  50072. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50073. }
  50074. if (result) {
  50075. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50076. return result;
  50077. }
  50078. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50079. };
  50080. /**
  50081. * Makes a copy of the animation
  50082. * @returns Cloned animation
  50083. */
  50084. Animation.prototype.clone = function () {
  50085. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50086. clone.enableBlending = this.enableBlending;
  50087. clone.blendingSpeed = this.blendingSpeed;
  50088. if (this._keys) {
  50089. clone.setKeys(this._keys);
  50090. }
  50091. if (this._ranges) {
  50092. clone._ranges = {};
  50093. for (var name in this._ranges) {
  50094. var range = this._ranges[name];
  50095. if (!range) {
  50096. continue;
  50097. }
  50098. clone._ranges[name] = range.clone();
  50099. }
  50100. }
  50101. return clone;
  50102. };
  50103. /**
  50104. * Sets the key frames of the animation
  50105. * @param values The animation key frames to set
  50106. */
  50107. Animation.prototype.setKeys = function (values) {
  50108. this._keys = values.slice(0);
  50109. };
  50110. /**
  50111. * Serializes the animation to an object
  50112. * @returns Serialized object
  50113. */
  50114. Animation.prototype.serialize = function () {
  50115. var serializationObject = {};
  50116. serializationObject.name = this.name;
  50117. serializationObject.property = this.targetProperty;
  50118. serializationObject.framePerSecond = this.framePerSecond;
  50119. serializationObject.dataType = this.dataType;
  50120. serializationObject.loopBehavior = this.loopMode;
  50121. serializationObject.enableBlending = this.enableBlending;
  50122. serializationObject.blendingSpeed = this.blendingSpeed;
  50123. var dataType = this.dataType;
  50124. serializationObject.keys = [];
  50125. var keys = this.getKeys();
  50126. for (var index = 0; index < keys.length; index++) {
  50127. var animationKey = keys[index];
  50128. var key = {};
  50129. key.frame = animationKey.frame;
  50130. switch (dataType) {
  50131. case Animation.ANIMATIONTYPE_FLOAT:
  50132. key.values = [animationKey.value];
  50133. break;
  50134. case Animation.ANIMATIONTYPE_QUATERNION:
  50135. case Animation.ANIMATIONTYPE_MATRIX:
  50136. case Animation.ANIMATIONTYPE_VECTOR3:
  50137. case Animation.ANIMATIONTYPE_COLOR3:
  50138. key.values = animationKey.value.asArray();
  50139. break;
  50140. }
  50141. serializationObject.keys.push(key);
  50142. }
  50143. serializationObject.ranges = [];
  50144. for (var name in this._ranges) {
  50145. var source = this._ranges[name];
  50146. if (!source) {
  50147. continue;
  50148. }
  50149. var range = {};
  50150. range.name = name;
  50151. range.from = source.from;
  50152. range.to = source.to;
  50153. serializationObject.ranges.push(range);
  50154. }
  50155. return serializationObject;
  50156. };
  50157. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50158. /**
  50159. * Get the float animation type
  50160. */
  50161. get: function () {
  50162. return Animation._ANIMATIONTYPE_FLOAT;
  50163. },
  50164. enumerable: true,
  50165. configurable: true
  50166. });
  50167. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50168. /**
  50169. * Get the Vector3 animation type
  50170. */
  50171. get: function () {
  50172. return Animation._ANIMATIONTYPE_VECTOR3;
  50173. },
  50174. enumerable: true,
  50175. configurable: true
  50176. });
  50177. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50178. /**
  50179. * Get the Vectpr2 animation type
  50180. */
  50181. get: function () {
  50182. return Animation._ANIMATIONTYPE_VECTOR2;
  50183. },
  50184. enumerable: true,
  50185. configurable: true
  50186. });
  50187. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50188. /**
  50189. * Get the Size animation type
  50190. */
  50191. get: function () {
  50192. return Animation._ANIMATIONTYPE_SIZE;
  50193. },
  50194. enumerable: true,
  50195. configurable: true
  50196. });
  50197. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50198. /**
  50199. * Get the Quaternion animation type
  50200. */
  50201. get: function () {
  50202. return Animation._ANIMATIONTYPE_QUATERNION;
  50203. },
  50204. enumerable: true,
  50205. configurable: true
  50206. });
  50207. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50208. /**
  50209. * Get the Matrix animation type
  50210. */
  50211. get: function () {
  50212. return Animation._ANIMATIONTYPE_MATRIX;
  50213. },
  50214. enumerable: true,
  50215. configurable: true
  50216. });
  50217. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50218. /**
  50219. * Get the Color3 animation type
  50220. */
  50221. get: function () {
  50222. return Animation._ANIMATIONTYPE_COLOR3;
  50223. },
  50224. enumerable: true,
  50225. configurable: true
  50226. });
  50227. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50228. /**
  50229. * Get the Relative Loop Mode
  50230. */
  50231. get: function () {
  50232. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50233. },
  50234. enumerable: true,
  50235. configurable: true
  50236. });
  50237. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50238. /**
  50239. * Get the Cycle Loop Mode
  50240. */
  50241. get: function () {
  50242. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50243. },
  50244. enumerable: true,
  50245. configurable: true
  50246. });
  50247. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50248. /**
  50249. * Get the Constant Loop Mode
  50250. */
  50251. get: function () {
  50252. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50253. },
  50254. enumerable: true,
  50255. configurable: true
  50256. });
  50257. /** @hidden */
  50258. Animation._UniversalLerp = function (left, right, amount) {
  50259. var constructor = left.constructor;
  50260. if (constructor.Lerp) { // Lerp supported
  50261. return constructor.Lerp(left, right, amount);
  50262. }
  50263. else if (constructor.Slerp) { // Slerp supported
  50264. return constructor.Slerp(left, right, amount);
  50265. }
  50266. else if (left.toFixed) { // Number
  50267. return left * (1.0 - amount) + amount * right;
  50268. }
  50269. else { // Blending not supported
  50270. return right;
  50271. }
  50272. };
  50273. /**
  50274. * Parses an animation object and creates an animation
  50275. * @param parsedAnimation Parsed animation object
  50276. * @returns Animation object
  50277. */
  50278. Animation.Parse = function (parsedAnimation) {
  50279. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50280. var dataType = parsedAnimation.dataType;
  50281. var keys = [];
  50282. var data;
  50283. var index;
  50284. if (parsedAnimation.enableBlending) {
  50285. animation.enableBlending = parsedAnimation.enableBlending;
  50286. }
  50287. if (parsedAnimation.blendingSpeed) {
  50288. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50289. }
  50290. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50291. var key = parsedAnimation.keys[index];
  50292. var inTangent;
  50293. var outTangent;
  50294. switch (dataType) {
  50295. case Animation.ANIMATIONTYPE_FLOAT:
  50296. data = key.values[0];
  50297. if (key.values.length >= 1) {
  50298. inTangent = key.values[1];
  50299. }
  50300. if (key.values.length >= 2) {
  50301. outTangent = key.values[2];
  50302. }
  50303. break;
  50304. case Animation.ANIMATIONTYPE_QUATERNION:
  50305. data = BABYLON.Quaternion.FromArray(key.values);
  50306. if (key.values.length >= 8) {
  50307. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50308. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50309. inTangent = _inTangent;
  50310. }
  50311. }
  50312. if (key.values.length >= 12) {
  50313. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50314. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50315. outTangent = _outTangent;
  50316. }
  50317. }
  50318. break;
  50319. case Animation.ANIMATIONTYPE_MATRIX:
  50320. data = BABYLON.Matrix.FromArray(key.values);
  50321. break;
  50322. case Animation.ANIMATIONTYPE_COLOR3:
  50323. data = BABYLON.Color3.FromArray(key.values);
  50324. break;
  50325. case Animation.ANIMATIONTYPE_VECTOR3:
  50326. default:
  50327. data = BABYLON.Vector3.FromArray(key.values);
  50328. break;
  50329. }
  50330. var keyData = {};
  50331. keyData.frame = key.frame;
  50332. keyData.value = data;
  50333. if (inTangent != undefined) {
  50334. keyData.inTangent = inTangent;
  50335. }
  50336. if (outTangent != undefined) {
  50337. keyData.outTangent = outTangent;
  50338. }
  50339. keys.push(keyData);
  50340. }
  50341. animation.setKeys(keys);
  50342. if (parsedAnimation.ranges) {
  50343. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50344. data = parsedAnimation.ranges[index];
  50345. animation.createRange(data.name, data.from, data.to);
  50346. }
  50347. }
  50348. return animation;
  50349. };
  50350. /**
  50351. * Appends the serialized animations from the source animations
  50352. * @param source Source containing the animations
  50353. * @param destination Target to store the animations
  50354. */
  50355. Animation.AppendSerializedAnimations = function (source, destination) {
  50356. if (source.animations) {
  50357. destination.animations = [];
  50358. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50359. var animation = source.animations[animationIndex];
  50360. destination.animations.push(animation.serialize());
  50361. }
  50362. }
  50363. };
  50364. /**
  50365. * Use matrix interpolation instead of using direct key value when animating matrices
  50366. */
  50367. Animation.AllowMatricesInterpolation = false;
  50368. /**
  50369. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50370. */
  50371. Animation.AllowMatrixDecomposeForInterpolation = true;
  50372. // Statics
  50373. /**
  50374. * Float animation type
  50375. */
  50376. Animation._ANIMATIONTYPE_FLOAT = 0;
  50377. /**
  50378. * Vector3 animation type
  50379. */
  50380. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50381. /**
  50382. * Quaternion animation type
  50383. */
  50384. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50385. /**
  50386. * Matrix animation type
  50387. */
  50388. Animation._ANIMATIONTYPE_MATRIX = 3;
  50389. /**
  50390. * Color3 animation type
  50391. */
  50392. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50393. /**
  50394. * Vector2 animation type
  50395. */
  50396. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50397. /**
  50398. * Size animation type
  50399. */
  50400. Animation._ANIMATIONTYPE_SIZE = 6;
  50401. /**
  50402. * Relative Loop Mode
  50403. */
  50404. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50405. /**
  50406. * Cycle Loop Mode
  50407. */
  50408. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50409. /**
  50410. * Constant Loop Mode
  50411. */
  50412. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50413. return Animation;
  50414. }());
  50415. BABYLON.Animation = Animation;
  50416. })(BABYLON || (BABYLON = {}));
  50417. //# sourceMappingURL=babylon.animation.js.map
  50418. var BABYLON;
  50419. (function (BABYLON) {
  50420. /**
  50421. * This class defines the direct association between an animation and a target
  50422. */
  50423. var TargetedAnimation = /** @class */ (function () {
  50424. function TargetedAnimation() {
  50425. }
  50426. return TargetedAnimation;
  50427. }());
  50428. BABYLON.TargetedAnimation = TargetedAnimation;
  50429. /**
  50430. * Use this class to create coordinated animations on multiple targets
  50431. */
  50432. var AnimationGroup = /** @class */ (function () {
  50433. function AnimationGroup(name, scene) {
  50434. if (scene === void 0) { scene = null; }
  50435. this.name = name;
  50436. this._targetedAnimations = new Array();
  50437. this._animatables = new Array();
  50438. this._from = Number.MAX_VALUE;
  50439. this._to = -Number.MAX_VALUE;
  50440. this._speedRatio = 1;
  50441. this.onAnimationEndObservable = new BABYLON.Observable();
  50442. /**
  50443. * This observable will notify when all animations have ended.
  50444. */
  50445. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50446. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50447. this._scene.animationGroups.push(this);
  50448. }
  50449. Object.defineProperty(AnimationGroup.prototype, "from", {
  50450. /**
  50451. * Gets the first frame
  50452. */
  50453. get: function () {
  50454. return this._from;
  50455. },
  50456. enumerable: true,
  50457. configurable: true
  50458. });
  50459. Object.defineProperty(AnimationGroup.prototype, "to", {
  50460. /**
  50461. * Gets the last frame
  50462. */
  50463. get: function () {
  50464. return this._to;
  50465. },
  50466. enumerable: true,
  50467. configurable: true
  50468. });
  50469. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50470. /**
  50471. * Define if the animations are started
  50472. */
  50473. get: function () {
  50474. return this._isStarted;
  50475. },
  50476. enumerable: true,
  50477. configurable: true
  50478. });
  50479. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50480. /**
  50481. * Gets or sets the speed ratio to use for all animations
  50482. */
  50483. get: function () {
  50484. return this._speedRatio;
  50485. },
  50486. /**
  50487. * Gets or sets the speed ratio to use for all animations
  50488. */
  50489. set: function (value) {
  50490. if (this._speedRatio === value) {
  50491. return;
  50492. }
  50493. this._speedRatio = value;
  50494. for (var index = 0; index < this._animatables.length; index++) {
  50495. var animatable = this._animatables[index];
  50496. animatable.speedRatio = this._speedRatio;
  50497. }
  50498. },
  50499. enumerable: true,
  50500. configurable: true
  50501. });
  50502. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50503. /**
  50504. * Gets the targeted animations for this animation group
  50505. */
  50506. get: function () {
  50507. return this._targetedAnimations;
  50508. },
  50509. enumerable: true,
  50510. configurable: true
  50511. });
  50512. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50513. /**
  50514. * returning the list of animatables controlled by this animation group.
  50515. */
  50516. get: function () {
  50517. return this._animatables;
  50518. },
  50519. enumerable: true,
  50520. configurable: true
  50521. });
  50522. /**
  50523. * Add an animation (with its target) in the group
  50524. * @param animation defines the animation we want to add
  50525. * @param target defines the target of the animation
  50526. * @returns the {BABYLON.TargetedAnimation} object
  50527. */
  50528. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50529. var targetedAnimation = {
  50530. animation: animation,
  50531. target: target
  50532. };
  50533. var keys = animation.getKeys();
  50534. if (this._from > keys[0].frame) {
  50535. this._from = keys[0].frame;
  50536. }
  50537. if (this._to < keys[keys.length - 1].frame) {
  50538. this._to = keys[keys.length - 1].frame;
  50539. }
  50540. this._targetedAnimations.push(targetedAnimation);
  50541. return targetedAnimation;
  50542. };
  50543. /**
  50544. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50545. * It can add constant keys at begin or end
  50546. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50547. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50548. */
  50549. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50550. if (beginFrame === void 0) { beginFrame = null; }
  50551. if (endFrame === void 0) { endFrame = null; }
  50552. if (beginFrame == null)
  50553. beginFrame = this._from;
  50554. if (endFrame == null)
  50555. endFrame = this._to;
  50556. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50557. var targetedAnimation = this._targetedAnimations[index];
  50558. var keys = targetedAnimation.animation.getKeys();
  50559. var startKey = keys[0];
  50560. var endKey = keys[keys.length - 1];
  50561. if (startKey.frame > beginFrame) {
  50562. var newKey = {
  50563. frame: beginFrame,
  50564. value: startKey.value,
  50565. inTangent: startKey.inTangent,
  50566. outTangent: startKey.outTangent,
  50567. interpolation: startKey.interpolation
  50568. };
  50569. keys.splice(0, 0, newKey);
  50570. }
  50571. if (endKey.frame < endFrame) {
  50572. var newKey = {
  50573. frame: endFrame,
  50574. value: endKey.value,
  50575. inTangent: endKey.outTangent,
  50576. outTangent: endKey.outTangent,
  50577. interpolation: endKey.interpolation
  50578. };
  50579. keys.push(newKey);
  50580. }
  50581. }
  50582. this._from = beginFrame;
  50583. this._to = endFrame;
  50584. return this;
  50585. };
  50586. /**
  50587. * Start all animations on given targets
  50588. * @param loop defines if animations must loop
  50589. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50590. * @param from defines the from key (optional)
  50591. * @param to defines the to key (optional)
  50592. * @returns the current animation group
  50593. */
  50594. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50595. var _this = this;
  50596. if (loop === void 0) { loop = false; }
  50597. if (speedRatio === void 0) { speedRatio = 1; }
  50598. if (this._isStarted || this._targetedAnimations.length === 0) {
  50599. return this;
  50600. }
  50601. var _loop_1 = function (targetedAnimation) {
  50602. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50603. animatable.onAnimationEnd = function () {
  50604. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50605. _this._checkAnimationGroupEnded(animatable);
  50606. };
  50607. this_1._animatables.push(animatable);
  50608. };
  50609. var this_1 = this;
  50610. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50611. var targetedAnimation = _a[_i];
  50612. _loop_1(targetedAnimation);
  50613. }
  50614. this._speedRatio = speedRatio;
  50615. this._isStarted = true;
  50616. return this;
  50617. };
  50618. /**
  50619. * Pause all animations
  50620. */
  50621. AnimationGroup.prototype.pause = function () {
  50622. if (!this._isStarted) {
  50623. return this;
  50624. }
  50625. for (var index = 0; index < this._animatables.length; index++) {
  50626. var animatable = this._animatables[index];
  50627. animatable.pause();
  50628. }
  50629. return this;
  50630. };
  50631. /**
  50632. * Play all animations to initial state
  50633. * This function will start() the animations if they were not started or will restart() them if they were paused
  50634. * @param loop defines if animations must loop
  50635. */
  50636. AnimationGroup.prototype.play = function (loop) {
  50637. // only if all animatables are ready and exist
  50638. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50639. if (loop !== undefined) {
  50640. for (var index = 0; index < this._animatables.length; index++) {
  50641. var animatable = this._animatables[index];
  50642. animatable.loopAnimation = loop;
  50643. }
  50644. }
  50645. this.restart();
  50646. }
  50647. else {
  50648. this.stop();
  50649. this.start(loop, this._speedRatio);
  50650. }
  50651. return this;
  50652. };
  50653. /**
  50654. * Reset all animations to initial state
  50655. */
  50656. AnimationGroup.prototype.reset = function () {
  50657. if (!this._isStarted) {
  50658. return this;
  50659. }
  50660. for (var index = 0; index < this._animatables.length; index++) {
  50661. var animatable = this._animatables[index];
  50662. animatable.reset();
  50663. }
  50664. return this;
  50665. };
  50666. /**
  50667. * Restart animations from key 0
  50668. */
  50669. AnimationGroup.prototype.restart = function () {
  50670. if (!this._isStarted) {
  50671. return this;
  50672. }
  50673. for (var index = 0; index < this._animatables.length; index++) {
  50674. var animatable = this._animatables[index];
  50675. animatable.restart();
  50676. }
  50677. return this;
  50678. };
  50679. /**
  50680. * Stop all animations
  50681. */
  50682. AnimationGroup.prototype.stop = function () {
  50683. if (!this._isStarted) {
  50684. return this;
  50685. }
  50686. var list = this._animatables.slice();
  50687. for (var index = 0; index < list.length; index++) {
  50688. list[index].stop();
  50689. }
  50690. this._isStarted = false;
  50691. return this;
  50692. };
  50693. /**
  50694. * Set animation weight for all animatables
  50695. * @param weight defines the weight to use
  50696. * @return the animationGroup
  50697. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50698. */
  50699. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50700. for (var index = 0; index < this._animatables.length; index++) {
  50701. var animatable = this._animatables[index];
  50702. animatable.weight = weight;
  50703. }
  50704. return this;
  50705. };
  50706. /**
  50707. * Synchronize and normalize all animatables with a source animatable
  50708. * @param root defines the root animatable to synchronize with
  50709. * @return the animationGroup
  50710. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50711. */
  50712. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50713. for (var index = 0; index < this._animatables.length; index++) {
  50714. var animatable = this._animatables[index];
  50715. animatable.syncWith(root);
  50716. }
  50717. return this;
  50718. };
  50719. /**
  50720. * Goes to a specific frame in this animation group
  50721. * @param frame the frame number to go to
  50722. * @return the animationGroup
  50723. */
  50724. AnimationGroup.prototype.goToFrame = function (frame) {
  50725. if (!this._isStarted) {
  50726. return this;
  50727. }
  50728. for (var index = 0; index < this._animatables.length; index++) {
  50729. var animatable = this._animatables[index];
  50730. animatable.goToFrame(frame);
  50731. }
  50732. return this;
  50733. };
  50734. /**
  50735. * Dispose all associated resources
  50736. */
  50737. AnimationGroup.prototype.dispose = function () {
  50738. this._targetedAnimations = [];
  50739. this._animatables = [];
  50740. var index = this._scene.animationGroups.indexOf(this);
  50741. if (index > -1) {
  50742. this._scene.animationGroups.splice(index, 1);
  50743. }
  50744. };
  50745. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50746. // animatable should be taken out of the array
  50747. var idx = this._animatables.indexOf(animatable);
  50748. if (idx > -1) {
  50749. this._animatables.splice(idx, 1);
  50750. }
  50751. // all animatables were removed? animation group ended!
  50752. if (this._animatables.length === 0) {
  50753. this._isStarted = false;
  50754. this.onAnimationGroupEndObservable.notifyObservers(this);
  50755. }
  50756. };
  50757. return AnimationGroup;
  50758. }());
  50759. BABYLON.AnimationGroup = AnimationGroup;
  50760. })(BABYLON || (BABYLON = {}));
  50761. //# sourceMappingURL=babylon.animationGroup.js.map
  50762. var BABYLON;
  50763. (function (BABYLON) {
  50764. /**
  50765. * Defines a runtime animation
  50766. */
  50767. var RuntimeAnimation = /** @class */ (function () {
  50768. /**
  50769. * Create a new RuntimeAnimation object
  50770. * @param target defines the target of the animation
  50771. * @param animation defines the source animation object
  50772. * @param scene defines the hosting scene
  50773. * @param host defines the initiating Animatable
  50774. */
  50775. function RuntimeAnimation(target, animation, scene, host) {
  50776. var _this = this;
  50777. this._events = new Array();
  50778. /**
  50779. * The current frame of the runtime animation
  50780. */
  50781. this._currentFrame = 0;
  50782. /**
  50783. * The original value of the runtime animation
  50784. */
  50785. this._originalValue = new Array();
  50786. /**
  50787. * The offsets cache of the runtime animation
  50788. */
  50789. this._offsetsCache = {};
  50790. /**
  50791. * The high limits cache of the runtime animation
  50792. */
  50793. this._highLimitsCache = {};
  50794. /**
  50795. * Specifies if the runtime animation has been stopped
  50796. */
  50797. this._stopped = false;
  50798. /**
  50799. * The blending factor of the runtime animation
  50800. */
  50801. this._blendingFactor = 0;
  50802. /**
  50803. * The target path of the runtime animation
  50804. */
  50805. this._targetPath = "";
  50806. /**
  50807. * The weight of the runtime animation
  50808. */
  50809. this._weight = 1.0;
  50810. /**
  50811. * The ratio offset of the runtime animation
  50812. */
  50813. this._ratioOffset = 0;
  50814. /**
  50815. * The previous delay of the runtime animation
  50816. */
  50817. this._previousDelay = 0;
  50818. /**
  50819. * The previous ratio of the runtime animation
  50820. */
  50821. this._previousRatio = 0;
  50822. this._animation = animation;
  50823. this._target = target;
  50824. this._scene = scene;
  50825. this._host = host;
  50826. animation._runtimeAnimations.push(this);
  50827. // Cloning events locally
  50828. var events = animation.getEvents();
  50829. if (events && events.length > 0) {
  50830. events.forEach(function (e) {
  50831. _this._events.push(e._clone());
  50832. });
  50833. }
  50834. }
  50835. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50836. /**
  50837. * Gets the current frame of the runtime animation
  50838. */
  50839. get: function () {
  50840. return this._currentFrame;
  50841. },
  50842. enumerable: true,
  50843. configurable: true
  50844. });
  50845. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50846. /**
  50847. * Gets the weight of the runtime animation
  50848. */
  50849. get: function () {
  50850. return this._weight;
  50851. },
  50852. enumerable: true,
  50853. configurable: true
  50854. });
  50855. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50856. /**
  50857. * Gets the current value of the runtime animation
  50858. */
  50859. get: function () {
  50860. return this._currentValue;
  50861. },
  50862. enumerable: true,
  50863. configurable: true
  50864. });
  50865. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50866. /**
  50867. * Gets the target path of the runtime animation
  50868. */
  50869. get: function () {
  50870. return this._targetPath;
  50871. },
  50872. enumerable: true,
  50873. configurable: true
  50874. });
  50875. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50876. /**
  50877. * Gets the actual target of the runtime animation
  50878. */
  50879. get: function () {
  50880. return this._activeTarget;
  50881. },
  50882. enumerable: true,
  50883. configurable: true
  50884. });
  50885. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50886. /**
  50887. * Gets the animation from the runtime animation
  50888. */
  50889. get: function () {
  50890. return this._animation;
  50891. },
  50892. enumerable: true,
  50893. configurable: true
  50894. });
  50895. /**
  50896. * Resets the runtime animation to the beginning
  50897. * @param restoreOriginal defines whether to restore the target property to the original value
  50898. */
  50899. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50900. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50901. if (restoreOriginal) {
  50902. if (this._target instanceof Array) {
  50903. var index = 0;
  50904. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50905. var target = _a[_i];
  50906. if (this._originalValue[index] !== undefined) {
  50907. this._setValue(target, this._originalValue[index], -1);
  50908. }
  50909. index++;
  50910. }
  50911. }
  50912. else {
  50913. if (this._originalValue[0] !== undefined) {
  50914. this._setValue(this._target, this._originalValue[0], -1);
  50915. }
  50916. }
  50917. }
  50918. this._offsetsCache = {};
  50919. this._highLimitsCache = {};
  50920. this._currentFrame = 0;
  50921. this._blendingFactor = 0;
  50922. this._originalValue = new Array();
  50923. // Events
  50924. for (var index = 0; index < this._events.length; index++) {
  50925. this._events[index].isDone = false;
  50926. }
  50927. };
  50928. /**
  50929. * Specifies if the runtime animation is stopped
  50930. * @returns Boolean specifying if the runtime animation is stopped
  50931. */
  50932. RuntimeAnimation.prototype.isStopped = function () {
  50933. return this._stopped;
  50934. };
  50935. /**
  50936. * Disposes of the runtime animation
  50937. */
  50938. RuntimeAnimation.prototype.dispose = function () {
  50939. var index = this._animation.runtimeAnimations.indexOf(this);
  50940. if (index > -1) {
  50941. this._animation.runtimeAnimations.splice(index, 1);
  50942. }
  50943. };
  50944. /**
  50945. * Interpolates the animation from the current frame
  50946. * @param currentFrame The frame to interpolate the animation to
  50947. * @param repeatCount The number of times that the animation should loop
  50948. * @param loopMode The type of looping mode to use
  50949. * @param offsetValue Animation offset value
  50950. * @param highLimitValue The high limit value
  50951. * @returns The interpolated value
  50952. */
  50953. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50954. this._currentFrame = currentFrame;
  50955. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50956. this._workValue = BABYLON.Matrix.Zero();
  50957. }
  50958. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50959. };
  50960. /**
  50961. * Apply the interpolated value to the target
  50962. * @param currentValue defines the value computed by the animation
  50963. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50964. */
  50965. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50966. if (weight === void 0) { weight = 1.0; }
  50967. if (this._target instanceof Array) {
  50968. var index = 0;
  50969. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50970. var target = _a[_i];
  50971. this._setValue(target, currentValue, weight, index);
  50972. index++;
  50973. }
  50974. }
  50975. else {
  50976. this._setValue(this._target, currentValue, weight);
  50977. }
  50978. };
  50979. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50980. if (targetIndex === void 0) { targetIndex = 0; }
  50981. // Set value
  50982. var path;
  50983. var destination;
  50984. var targetPropertyPath = this._animation.targetPropertyPath;
  50985. if (targetPropertyPath.length > 1) {
  50986. var property = target[targetPropertyPath[0]];
  50987. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50988. property = property[targetPropertyPath[index]];
  50989. }
  50990. path = targetPropertyPath[targetPropertyPath.length - 1];
  50991. destination = property;
  50992. }
  50993. else {
  50994. path = targetPropertyPath[0];
  50995. destination = target;
  50996. }
  50997. this._targetPath = path;
  50998. this._activeTarget = destination;
  50999. this._weight = weight;
  51000. if (this._originalValue[targetIndex] === undefined) {
  51001. var originalValue = void 0;
  51002. if (destination.getRestPose && path === "_matrix") { // For bones
  51003. originalValue = destination.getRestPose();
  51004. }
  51005. else {
  51006. originalValue = destination[path];
  51007. }
  51008. if (originalValue && originalValue.clone) {
  51009. this._originalValue[targetIndex] = originalValue.clone();
  51010. }
  51011. else {
  51012. this._originalValue[targetIndex] = originalValue;
  51013. }
  51014. }
  51015. // Blending
  51016. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51017. if (enableBlending && this._blendingFactor <= 1.0) {
  51018. if (!this._originalBlendValue) {
  51019. var originalValue = destination[path];
  51020. if (originalValue.clone) {
  51021. this._originalBlendValue = originalValue.clone();
  51022. }
  51023. else {
  51024. this._originalBlendValue = originalValue;
  51025. }
  51026. }
  51027. if (this._originalBlendValue.m) { // Matrix
  51028. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51029. if (this._currentValue) {
  51030. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51031. }
  51032. else {
  51033. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51034. }
  51035. }
  51036. else {
  51037. if (this._currentValue) {
  51038. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51039. }
  51040. else {
  51041. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51042. }
  51043. }
  51044. }
  51045. else {
  51046. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51047. }
  51048. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51049. this._blendingFactor += blendingSpeed;
  51050. }
  51051. else {
  51052. this._currentValue = currentValue;
  51053. }
  51054. if (weight !== -1.0) {
  51055. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51056. }
  51057. else {
  51058. destination[path] = this._currentValue;
  51059. }
  51060. if (target.markAsDirty) {
  51061. target.markAsDirty(this._animation.targetProperty);
  51062. }
  51063. };
  51064. /**
  51065. * Gets the loop pmode of the runtime animation
  51066. * @returns Loop Mode
  51067. */
  51068. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51069. if (this._target && this._target.animationPropertiesOverride) {
  51070. return this._target.animationPropertiesOverride.loopMode;
  51071. }
  51072. return this._animation.loopMode;
  51073. };
  51074. /**
  51075. * Move the current animation to a given frame
  51076. * @param frame defines the frame to move to
  51077. */
  51078. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51079. var keys = this._animation.getKeys();
  51080. if (frame < keys[0].frame) {
  51081. frame = keys[0].frame;
  51082. }
  51083. else if (frame > keys[keys.length - 1].frame) {
  51084. frame = keys[keys.length - 1].frame;
  51085. }
  51086. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51087. this.setValue(currentValue, -1);
  51088. };
  51089. /**
  51090. * @hidden Internal use only
  51091. */
  51092. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51093. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51094. this._ratioOffset = this._previousRatio - newRatio;
  51095. };
  51096. /**
  51097. * Execute the current animation
  51098. * @param delay defines the delay to add to the current frame
  51099. * @param from defines the lower bound of the animation range
  51100. * @param to defines the upper bound of the animation range
  51101. * @param loop defines if the current animation must loop
  51102. * @param speedRatio defines the current speed ratio
  51103. * @param weight defines the weight of the animation (default is -1 so no weight)
  51104. * @returns a boolean indicating if the animation has ended
  51105. */
  51106. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51107. if (weight === void 0) { weight = -1.0; }
  51108. var targetPropertyPath = this._animation.targetPropertyPath;
  51109. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51110. this._stopped = true;
  51111. return false;
  51112. }
  51113. var keys = this._animation.getKeys();
  51114. // Return immediately if there is only one key frame.
  51115. if (keys.length === 1) {
  51116. this.setValue(keys[0].value, weight);
  51117. return !loop;
  51118. }
  51119. var returnValue = true;
  51120. // Adding a start key at frame 0 if missing
  51121. if (keys[0].frame !== 0) {
  51122. var newKey = { frame: 0, value: keys[0].value };
  51123. keys.splice(0, 0, newKey);
  51124. }
  51125. // Check limits
  51126. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51127. from = keys[0].frame;
  51128. }
  51129. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51130. to = keys[keys.length - 1].frame;
  51131. }
  51132. //to and from cannot be the same key
  51133. if (from === to) {
  51134. if (from > keys[0].frame) {
  51135. from--;
  51136. }
  51137. else if (to < keys[keys.length - 1].frame) {
  51138. to++;
  51139. }
  51140. }
  51141. // Compute ratio
  51142. var range = to - from;
  51143. var offsetValue;
  51144. // ratio represents the frame delta between from and to
  51145. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51146. var highLimitValue = 0;
  51147. this._previousDelay = delay;
  51148. this._previousRatio = ratio;
  51149. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51150. returnValue = false;
  51151. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51152. }
  51153. else {
  51154. // Get max value if required
  51155. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51156. var keyOffset = to.toString() + from.toString();
  51157. if (!this._offsetsCache[keyOffset]) {
  51158. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51159. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51160. switch (this._animation.dataType) {
  51161. // Float
  51162. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51163. this._offsetsCache[keyOffset] = toValue - fromValue;
  51164. break;
  51165. // Quaternion
  51166. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51167. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51168. break;
  51169. // Vector3
  51170. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51171. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51172. // Vector2
  51173. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51174. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51175. // Size
  51176. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51177. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51178. // Color3
  51179. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51180. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51181. default:
  51182. break;
  51183. }
  51184. this._highLimitsCache[keyOffset] = toValue;
  51185. }
  51186. highLimitValue = this._highLimitsCache[keyOffset];
  51187. offsetValue = this._offsetsCache[keyOffset];
  51188. }
  51189. }
  51190. if (offsetValue === undefined) {
  51191. switch (this._animation.dataType) {
  51192. // Float
  51193. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51194. offsetValue = 0;
  51195. break;
  51196. // Quaternion
  51197. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51198. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51199. break;
  51200. // Vector3
  51201. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51202. offsetValue = BABYLON.Vector3.Zero();
  51203. break;
  51204. // Vector2
  51205. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51206. offsetValue = BABYLON.Vector2.Zero();
  51207. break;
  51208. // Size
  51209. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51210. offsetValue = BABYLON.Size.Zero();
  51211. break;
  51212. // Color3
  51213. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51214. offsetValue = BABYLON.Color3.Black();
  51215. }
  51216. }
  51217. // Compute value
  51218. var repeatCount = (ratio / range) >> 0;
  51219. var currentFrame = returnValue ? from + ratio % range : to;
  51220. // Need to normalize?
  51221. if (this._host && this._host.syncRoot) {
  51222. var syncRoot = this._host.syncRoot;
  51223. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51224. currentFrame = from + (to - from) * hostNormalizedFrame;
  51225. }
  51226. // Reset events if looping
  51227. var events = this._events;
  51228. if (range > 0 && this.currentFrame > currentFrame ||
  51229. range < 0 && this.currentFrame < currentFrame) {
  51230. // Need to reset animation events
  51231. for (var index = 0; index < events.length; index++) {
  51232. if (!events[index].onlyOnce) {
  51233. // reset event, the animation is looping
  51234. events[index].isDone = false;
  51235. }
  51236. }
  51237. }
  51238. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51239. // Set value
  51240. this.setValue(currentValue, weight);
  51241. // Check events
  51242. for (var index = 0; index < events.length; index++) {
  51243. // Make sure current frame has passed event frame and that event frame is within the current range
  51244. // Also, handle both forward and reverse animations
  51245. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51246. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51247. var event = events[index];
  51248. if (!event.isDone) {
  51249. // If event should be done only once, remove it.
  51250. if (event.onlyOnce) {
  51251. events.splice(index, 1);
  51252. index--;
  51253. }
  51254. event.isDone = true;
  51255. event.action();
  51256. } // Don't do anything if the event has already be done.
  51257. }
  51258. }
  51259. if (!returnValue) {
  51260. this._stopped = true;
  51261. }
  51262. return returnValue;
  51263. };
  51264. return RuntimeAnimation;
  51265. }());
  51266. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51267. })(BABYLON || (BABYLON = {}));
  51268. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51269. var BABYLON;
  51270. (function (BABYLON) {
  51271. var Animatable = /** @class */ (function () {
  51272. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51273. if (fromFrame === void 0) { fromFrame = 0; }
  51274. if (toFrame === void 0) { toFrame = 100; }
  51275. if (loopAnimation === void 0) { loopAnimation = false; }
  51276. if (speedRatio === void 0) { speedRatio = 1.0; }
  51277. this.target = target;
  51278. this.fromFrame = fromFrame;
  51279. this.toFrame = toFrame;
  51280. this.loopAnimation = loopAnimation;
  51281. this.onAnimationEnd = onAnimationEnd;
  51282. this._localDelayOffset = null;
  51283. this._pausedDelay = null;
  51284. this._runtimeAnimations = new Array();
  51285. this._paused = false;
  51286. this._speedRatio = 1;
  51287. this._weight = -1.0;
  51288. this.animationStarted = false;
  51289. /**
  51290. * Observer raised when the animation ends
  51291. */
  51292. this.onAnimationEndObservable = new BABYLON.Observable();
  51293. this._scene = scene;
  51294. if (animations) {
  51295. this.appendAnimations(target, animations);
  51296. }
  51297. this._speedRatio = speedRatio;
  51298. scene._activeAnimatables.push(this);
  51299. }
  51300. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51301. /**
  51302. * Gets the root Animatable used to synchronize and normalize animations
  51303. */
  51304. get: function () {
  51305. return this._syncRoot;
  51306. },
  51307. enumerable: true,
  51308. configurable: true
  51309. });
  51310. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51311. /**
  51312. * Gets the current frame of the first RuntimeAnimation
  51313. * Used to synchronize Animatables
  51314. */
  51315. get: function () {
  51316. if (this._runtimeAnimations.length === 0) {
  51317. return 0;
  51318. }
  51319. return this._runtimeAnimations[0].currentFrame;
  51320. },
  51321. enumerable: true,
  51322. configurable: true
  51323. });
  51324. Object.defineProperty(Animatable.prototype, "weight", {
  51325. /**
  51326. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51327. */
  51328. get: function () {
  51329. return this._weight;
  51330. },
  51331. set: function (value) {
  51332. if (value === -1) { // -1 is ok and means no weight
  51333. this._weight = -1;
  51334. return;
  51335. }
  51336. // Else weight must be in [0, 1] range
  51337. this._weight = Math.min(Math.max(value, 0), 1.0);
  51338. },
  51339. enumerable: true,
  51340. configurable: true
  51341. });
  51342. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51343. /**
  51344. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51345. */
  51346. get: function () {
  51347. return this._speedRatio;
  51348. },
  51349. set: function (value) {
  51350. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51351. var animation = this._runtimeAnimations[index];
  51352. animation._prepareForSpeedRatioChange(value);
  51353. }
  51354. this._speedRatio = value;
  51355. },
  51356. enumerable: true,
  51357. configurable: true
  51358. });
  51359. // Methods
  51360. /**
  51361. * Synchronize and normalize current Animatable with a source Animatable
  51362. * This is useful when using animation weights and when animations are not of the same length
  51363. * @param root defines the root Animatable to synchronize with
  51364. * @returns the current Animatable
  51365. */
  51366. Animatable.prototype.syncWith = function (root) {
  51367. this._syncRoot = root;
  51368. if (root) {
  51369. // Make sure this animatable will animate after the root
  51370. var index = this._scene._activeAnimatables.indexOf(this);
  51371. if (index > -1) {
  51372. this._scene._activeAnimatables.splice(index, 1);
  51373. this._scene._activeAnimatables.push(this);
  51374. }
  51375. }
  51376. return this;
  51377. };
  51378. Animatable.prototype.getAnimations = function () {
  51379. return this._runtimeAnimations;
  51380. };
  51381. Animatable.prototype.appendAnimations = function (target, animations) {
  51382. for (var index = 0; index < animations.length; index++) {
  51383. var animation = animations[index];
  51384. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51385. }
  51386. };
  51387. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51388. var runtimeAnimations = this._runtimeAnimations;
  51389. for (var index = 0; index < runtimeAnimations.length; index++) {
  51390. if (runtimeAnimations[index].animation.targetProperty === property) {
  51391. return runtimeAnimations[index].animation;
  51392. }
  51393. }
  51394. return null;
  51395. };
  51396. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51397. var runtimeAnimations = this._runtimeAnimations;
  51398. for (var index = 0; index < runtimeAnimations.length; index++) {
  51399. if (runtimeAnimations[index].animation.targetProperty === property) {
  51400. return runtimeAnimations[index];
  51401. }
  51402. }
  51403. return null;
  51404. };
  51405. Animatable.prototype.reset = function () {
  51406. var runtimeAnimations = this._runtimeAnimations;
  51407. for (var index = 0; index < runtimeAnimations.length; index++) {
  51408. runtimeAnimations[index].reset(true);
  51409. }
  51410. this._localDelayOffset = null;
  51411. this._pausedDelay = null;
  51412. };
  51413. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51414. var runtimeAnimations = this._runtimeAnimations;
  51415. for (var index = 0; index < runtimeAnimations.length; index++) {
  51416. runtimeAnimations[index].animation.enableBlending = true;
  51417. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51418. }
  51419. };
  51420. Animatable.prototype.disableBlending = function () {
  51421. var runtimeAnimations = this._runtimeAnimations;
  51422. for (var index = 0; index < runtimeAnimations.length; index++) {
  51423. runtimeAnimations[index].animation.enableBlending = false;
  51424. }
  51425. };
  51426. Animatable.prototype.goToFrame = function (frame) {
  51427. var runtimeAnimations = this._runtimeAnimations;
  51428. if (runtimeAnimations[0]) {
  51429. var fps = runtimeAnimations[0].animation.framePerSecond;
  51430. var currentFrame = runtimeAnimations[0].currentFrame;
  51431. var adjustTime = frame - currentFrame;
  51432. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51433. if (this._localDelayOffset === null) {
  51434. this._localDelayOffset = 0;
  51435. }
  51436. this._localDelayOffset -= delay;
  51437. }
  51438. for (var index = 0; index < runtimeAnimations.length; index++) {
  51439. runtimeAnimations[index].goToFrame(frame);
  51440. }
  51441. };
  51442. Animatable.prototype.pause = function () {
  51443. if (this._paused) {
  51444. return;
  51445. }
  51446. this._paused = true;
  51447. };
  51448. Animatable.prototype.restart = function () {
  51449. this._paused = false;
  51450. };
  51451. Animatable.prototype._raiseOnAnimationEnd = function () {
  51452. if (this.onAnimationEnd) {
  51453. this.onAnimationEnd();
  51454. }
  51455. this.onAnimationEndObservable.notifyObservers(this);
  51456. };
  51457. Animatable.prototype.stop = function (animationName) {
  51458. if (animationName) {
  51459. var idx = this._scene._activeAnimatables.indexOf(this);
  51460. if (idx > -1) {
  51461. var runtimeAnimations = this._runtimeAnimations;
  51462. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51463. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51464. continue;
  51465. }
  51466. runtimeAnimations[index].dispose();
  51467. runtimeAnimations.splice(index, 1);
  51468. }
  51469. if (runtimeAnimations.length == 0) {
  51470. this._scene._activeAnimatables.splice(idx, 1);
  51471. this._raiseOnAnimationEnd();
  51472. }
  51473. }
  51474. }
  51475. else {
  51476. var index = this._scene._activeAnimatables.indexOf(this);
  51477. if (index > -1) {
  51478. this._scene._activeAnimatables.splice(index, 1);
  51479. var runtimeAnimations = this._runtimeAnimations;
  51480. for (var index = 0; index < runtimeAnimations.length; index++) {
  51481. runtimeAnimations[index].dispose();
  51482. }
  51483. this._raiseOnAnimationEnd();
  51484. }
  51485. }
  51486. };
  51487. /**
  51488. * Wait asynchronously for the animation to end
  51489. * @returns a promise which will be fullfilled when the animation ends
  51490. */
  51491. Animatable.prototype.waitAsync = function () {
  51492. var _this = this;
  51493. return new Promise(function (resolve, reject) {
  51494. _this.onAnimationEndObservable.add(function () {
  51495. resolve(_this);
  51496. }, undefined, undefined, _this, true);
  51497. });
  51498. };
  51499. /** @hidden */
  51500. Animatable.prototype._animate = function (delay) {
  51501. if (this._paused) {
  51502. this.animationStarted = false;
  51503. if (this._pausedDelay === null) {
  51504. this._pausedDelay = delay;
  51505. }
  51506. return true;
  51507. }
  51508. if (this._localDelayOffset === null) {
  51509. this._localDelayOffset = delay;
  51510. this._pausedDelay = null;
  51511. }
  51512. else if (this._pausedDelay !== null) {
  51513. this._localDelayOffset += delay - this._pausedDelay;
  51514. this._pausedDelay = null;
  51515. }
  51516. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51517. return true;
  51518. }
  51519. // Animating
  51520. var running = false;
  51521. var runtimeAnimations = this._runtimeAnimations;
  51522. var index;
  51523. for (index = 0; index < runtimeAnimations.length; index++) {
  51524. var animation = runtimeAnimations[index];
  51525. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51526. running = running || isRunning;
  51527. }
  51528. this.animationStarted = running;
  51529. if (!running) {
  51530. // Remove from active animatables
  51531. index = this._scene._activeAnimatables.indexOf(this);
  51532. this._scene._activeAnimatables.splice(index, 1);
  51533. // Dispose all runtime animations
  51534. for (index = 0; index < runtimeAnimations.length; index++) {
  51535. runtimeAnimations[index].dispose();
  51536. }
  51537. this._raiseOnAnimationEnd();
  51538. this.onAnimationEnd = null;
  51539. this.onAnimationEndObservable.clear();
  51540. }
  51541. return running;
  51542. };
  51543. return Animatable;
  51544. }());
  51545. BABYLON.Animatable = Animatable;
  51546. })(BABYLON || (BABYLON = {}));
  51547. //# sourceMappingURL=babylon.animatable.js.map
  51548. var BABYLON;
  51549. (function (BABYLON) {
  51550. var EasingFunction = /** @class */ (function () {
  51551. function EasingFunction() {
  51552. // Properties
  51553. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51554. }
  51555. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51556. get: function () {
  51557. return EasingFunction._EASINGMODE_EASEIN;
  51558. },
  51559. enumerable: true,
  51560. configurable: true
  51561. });
  51562. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51563. get: function () {
  51564. return EasingFunction._EASINGMODE_EASEOUT;
  51565. },
  51566. enumerable: true,
  51567. configurable: true
  51568. });
  51569. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51570. get: function () {
  51571. return EasingFunction._EASINGMODE_EASEINOUT;
  51572. },
  51573. enumerable: true,
  51574. configurable: true
  51575. });
  51576. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51577. var n = Math.min(Math.max(easingMode, 0), 2);
  51578. this._easingMode = n;
  51579. };
  51580. EasingFunction.prototype.getEasingMode = function () {
  51581. return this._easingMode;
  51582. };
  51583. EasingFunction.prototype.easeInCore = function (gradient) {
  51584. throw new Error('You must implement this method');
  51585. };
  51586. EasingFunction.prototype.ease = function (gradient) {
  51587. switch (this._easingMode) {
  51588. case EasingFunction.EASINGMODE_EASEIN:
  51589. return this.easeInCore(gradient);
  51590. case EasingFunction.EASINGMODE_EASEOUT:
  51591. return (1 - this.easeInCore(1 - gradient));
  51592. }
  51593. if (gradient >= 0.5) {
  51594. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51595. }
  51596. return (this.easeInCore(gradient * 2) * 0.5);
  51597. };
  51598. //Statics
  51599. EasingFunction._EASINGMODE_EASEIN = 0;
  51600. EasingFunction._EASINGMODE_EASEOUT = 1;
  51601. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51602. return EasingFunction;
  51603. }());
  51604. BABYLON.EasingFunction = EasingFunction;
  51605. var CircleEase = /** @class */ (function (_super) {
  51606. __extends(CircleEase, _super);
  51607. function CircleEase() {
  51608. return _super !== null && _super.apply(this, arguments) || this;
  51609. }
  51610. CircleEase.prototype.easeInCore = function (gradient) {
  51611. gradient = Math.max(0, Math.min(1, gradient));
  51612. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51613. };
  51614. return CircleEase;
  51615. }(EasingFunction));
  51616. BABYLON.CircleEase = CircleEase;
  51617. var BackEase = /** @class */ (function (_super) {
  51618. __extends(BackEase, _super);
  51619. function BackEase(amplitude) {
  51620. if (amplitude === void 0) { amplitude = 1; }
  51621. var _this = _super.call(this) || this;
  51622. _this.amplitude = amplitude;
  51623. return _this;
  51624. }
  51625. BackEase.prototype.easeInCore = function (gradient) {
  51626. var num = Math.max(0, this.amplitude);
  51627. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51628. };
  51629. return BackEase;
  51630. }(EasingFunction));
  51631. BABYLON.BackEase = BackEase;
  51632. var BounceEase = /** @class */ (function (_super) {
  51633. __extends(BounceEase, _super);
  51634. function BounceEase(bounces, bounciness) {
  51635. if (bounces === void 0) { bounces = 3; }
  51636. if (bounciness === void 0) { bounciness = 2; }
  51637. var _this = _super.call(this) || this;
  51638. _this.bounces = bounces;
  51639. _this.bounciness = bounciness;
  51640. return _this;
  51641. }
  51642. BounceEase.prototype.easeInCore = function (gradient) {
  51643. var y = Math.max(0.0, this.bounces);
  51644. var bounciness = this.bounciness;
  51645. if (bounciness <= 1.0) {
  51646. bounciness = 1.001;
  51647. }
  51648. var num9 = Math.pow(bounciness, y);
  51649. var num5 = 1.0 - bounciness;
  51650. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51651. var num15 = gradient * num4;
  51652. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51653. var num3 = Math.floor(num65);
  51654. var num13 = num3 + 1.0;
  51655. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51656. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51657. var num7 = (num8 + num12) * 0.5;
  51658. var num6 = gradient - num7;
  51659. var num2 = num7 - num8;
  51660. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51661. };
  51662. return BounceEase;
  51663. }(EasingFunction));
  51664. BABYLON.BounceEase = BounceEase;
  51665. var CubicEase = /** @class */ (function (_super) {
  51666. __extends(CubicEase, _super);
  51667. function CubicEase() {
  51668. return _super !== null && _super.apply(this, arguments) || this;
  51669. }
  51670. CubicEase.prototype.easeInCore = function (gradient) {
  51671. return (gradient * gradient * gradient);
  51672. };
  51673. return CubicEase;
  51674. }(EasingFunction));
  51675. BABYLON.CubicEase = CubicEase;
  51676. var ElasticEase = /** @class */ (function (_super) {
  51677. __extends(ElasticEase, _super);
  51678. function ElasticEase(oscillations, springiness) {
  51679. if (oscillations === void 0) { oscillations = 3; }
  51680. if (springiness === void 0) { springiness = 3; }
  51681. var _this = _super.call(this) || this;
  51682. _this.oscillations = oscillations;
  51683. _this.springiness = springiness;
  51684. return _this;
  51685. }
  51686. ElasticEase.prototype.easeInCore = function (gradient) {
  51687. var num2;
  51688. var num3 = Math.max(0.0, this.oscillations);
  51689. var num = Math.max(0.0, this.springiness);
  51690. if (num == 0) {
  51691. num2 = gradient;
  51692. }
  51693. else {
  51694. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51695. }
  51696. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51697. };
  51698. return ElasticEase;
  51699. }(EasingFunction));
  51700. BABYLON.ElasticEase = ElasticEase;
  51701. var ExponentialEase = /** @class */ (function (_super) {
  51702. __extends(ExponentialEase, _super);
  51703. function ExponentialEase(exponent) {
  51704. if (exponent === void 0) { exponent = 2; }
  51705. var _this = _super.call(this) || this;
  51706. _this.exponent = exponent;
  51707. return _this;
  51708. }
  51709. ExponentialEase.prototype.easeInCore = function (gradient) {
  51710. if (this.exponent <= 0) {
  51711. return gradient;
  51712. }
  51713. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51714. };
  51715. return ExponentialEase;
  51716. }(EasingFunction));
  51717. BABYLON.ExponentialEase = ExponentialEase;
  51718. var PowerEase = /** @class */ (function (_super) {
  51719. __extends(PowerEase, _super);
  51720. function PowerEase(power) {
  51721. if (power === void 0) { power = 2; }
  51722. var _this = _super.call(this) || this;
  51723. _this.power = power;
  51724. return _this;
  51725. }
  51726. PowerEase.prototype.easeInCore = function (gradient) {
  51727. var y = Math.max(0.0, this.power);
  51728. return Math.pow(gradient, y);
  51729. };
  51730. return PowerEase;
  51731. }(EasingFunction));
  51732. BABYLON.PowerEase = PowerEase;
  51733. var QuadraticEase = /** @class */ (function (_super) {
  51734. __extends(QuadraticEase, _super);
  51735. function QuadraticEase() {
  51736. return _super !== null && _super.apply(this, arguments) || this;
  51737. }
  51738. QuadraticEase.prototype.easeInCore = function (gradient) {
  51739. return (gradient * gradient);
  51740. };
  51741. return QuadraticEase;
  51742. }(EasingFunction));
  51743. BABYLON.QuadraticEase = QuadraticEase;
  51744. var QuarticEase = /** @class */ (function (_super) {
  51745. __extends(QuarticEase, _super);
  51746. function QuarticEase() {
  51747. return _super !== null && _super.apply(this, arguments) || this;
  51748. }
  51749. QuarticEase.prototype.easeInCore = function (gradient) {
  51750. return (gradient * gradient * gradient * gradient);
  51751. };
  51752. return QuarticEase;
  51753. }(EasingFunction));
  51754. BABYLON.QuarticEase = QuarticEase;
  51755. var QuinticEase = /** @class */ (function (_super) {
  51756. __extends(QuinticEase, _super);
  51757. function QuinticEase() {
  51758. return _super !== null && _super.apply(this, arguments) || this;
  51759. }
  51760. QuinticEase.prototype.easeInCore = function (gradient) {
  51761. return (gradient * gradient * gradient * gradient * gradient);
  51762. };
  51763. return QuinticEase;
  51764. }(EasingFunction));
  51765. BABYLON.QuinticEase = QuinticEase;
  51766. var SineEase = /** @class */ (function (_super) {
  51767. __extends(SineEase, _super);
  51768. function SineEase() {
  51769. return _super !== null && _super.apply(this, arguments) || this;
  51770. }
  51771. SineEase.prototype.easeInCore = function (gradient) {
  51772. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51773. };
  51774. return SineEase;
  51775. }(EasingFunction));
  51776. BABYLON.SineEase = SineEase;
  51777. var BezierCurveEase = /** @class */ (function (_super) {
  51778. __extends(BezierCurveEase, _super);
  51779. function BezierCurveEase(x1, y1, x2, y2) {
  51780. if (x1 === void 0) { x1 = 0; }
  51781. if (y1 === void 0) { y1 = 0; }
  51782. if (x2 === void 0) { x2 = 1; }
  51783. if (y2 === void 0) { y2 = 1; }
  51784. var _this = _super.call(this) || this;
  51785. _this.x1 = x1;
  51786. _this.y1 = y1;
  51787. _this.x2 = x2;
  51788. _this.y2 = y2;
  51789. return _this;
  51790. }
  51791. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51792. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51793. };
  51794. return BezierCurveEase;
  51795. }(EasingFunction));
  51796. BABYLON.BezierCurveEase = BezierCurveEase;
  51797. })(BABYLON || (BABYLON = {}));
  51798. //# sourceMappingURL=babylon.easing.js.map
  51799. var BABYLON;
  51800. (function (BABYLON) {
  51801. /**
  51802. * A Condition applied to an Action
  51803. */
  51804. var Condition = /** @class */ (function () {
  51805. /**
  51806. * Creates a new Condition
  51807. * @param actionManager the manager of the action the condition is applied to
  51808. */
  51809. function Condition(actionManager) {
  51810. this._actionManager = actionManager;
  51811. }
  51812. /**
  51813. * Check if the current condition is valid
  51814. * @returns a boolean
  51815. */
  51816. Condition.prototype.isValid = function () {
  51817. return true;
  51818. };
  51819. /**
  51820. * Internal only
  51821. * @hidden
  51822. */
  51823. Condition.prototype._getProperty = function (propertyPath) {
  51824. return this._actionManager._getProperty(propertyPath);
  51825. };
  51826. /**
  51827. * Internal only
  51828. * @hidden
  51829. */
  51830. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51831. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51832. };
  51833. /**
  51834. * Serialize placeholder for child classes
  51835. * @returns the serialized object
  51836. */
  51837. Condition.prototype.serialize = function () {
  51838. };
  51839. /**
  51840. * Internal only
  51841. * @hidden
  51842. */
  51843. Condition.prototype._serialize = function (serializedCondition) {
  51844. return {
  51845. type: 2,
  51846. children: [],
  51847. name: serializedCondition.name,
  51848. properties: serializedCondition.properties
  51849. };
  51850. };
  51851. return Condition;
  51852. }());
  51853. BABYLON.Condition = Condition;
  51854. /**
  51855. * Defines specific conditional operators as extensions of Condition
  51856. */
  51857. var ValueCondition = /** @class */ (function (_super) {
  51858. __extends(ValueCondition, _super);
  51859. /**
  51860. * Creates a new ValueCondition
  51861. * @param actionManager manager for the action the condition applies to
  51862. * @param target for the action
  51863. * @param propertyPath path to specify the property of the target the conditional operator uses
  51864. * @param value the value compared by the conditional operator against the current value of the property
  51865. * @param operator the conditional operator, default ValueCondition.IsEqual
  51866. */
  51867. function ValueCondition(actionManager, target,
  51868. /** path to specify the property of the target the conditional operator uses */
  51869. propertyPath,
  51870. /** the value compared by the conditional operator against the current value of the property */
  51871. value,
  51872. /** the conditional operator, default ValueCondition.IsEqual */
  51873. operator) {
  51874. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51875. var _this = _super.call(this, actionManager) || this;
  51876. _this.propertyPath = propertyPath;
  51877. _this.value = value;
  51878. _this.operator = operator;
  51879. _this._target = target;
  51880. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51881. _this._property = _this._getProperty(_this.propertyPath);
  51882. return _this;
  51883. }
  51884. Object.defineProperty(ValueCondition, "IsEqual", {
  51885. /**
  51886. * returns the number for IsEqual
  51887. */
  51888. get: function () {
  51889. return ValueCondition._IsEqual;
  51890. },
  51891. enumerable: true,
  51892. configurable: true
  51893. });
  51894. Object.defineProperty(ValueCondition, "IsDifferent", {
  51895. /**
  51896. * Returns the number for IsDifferent
  51897. */
  51898. get: function () {
  51899. return ValueCondition._IsDifferent;
  51900. },
  51901. enumerable: true,
  51902. configurable: true
  51903. });
  51904. Object.defineProperty(ValueCondition, "IsGreater", {
  51905. /**
  51906. * Returns the number for IsGreater
  51907. */
  51908. get: function () {
  51909. return ValueCondition._IsGreater;
  51910. },
  51911. enumerable: true,
  51912. configurable: true
  51913. });
  51914. Object.defineProperty(ValueCondition, "IsLesser", {
  51915. /**
  51916. * Returns the number for IsLesser
  51917. */
  51918. get: function () {
  51919. return ValueCondition._IsLesser;
  51920. },
  51921. enumerable: true,
  51922. configurable: true
  51923. });
  51924. /**
  51925. * Compares the given value with the property value for the specified conditional operator
  51926. * @returns the result of the comparison
  51927. */
  51928. ValueCondition.prototype.isValid = function () {
  51929. switch (this.operator) {
  51930. case ValueCondition.IsGreater:
  51931. return this._effectiveTarget[this._property] > this.value;
  51932. case ValueCondition.IsLesser:
  51933. return this._effectiveTarget[this._property] < this.value;
  51934. case ValueCondition.IsEqual:
  51935. case ValueCondition.IsDifferent:
  51936. var check;
  51937. if (this.value.equals) {
  51938. check = this.value.equals(this._effectiveTarget[this._property]);
  51939. }
  51940. else {
  51941. check = this.value === this._effectiveTarget[this._property];
  51942. }
  51943. return this.operator === ValueCondition.IsEqual ? check : !check;
  51944. }
  51945. return false;
  51946. };
  51947. /**
  51948. * Serialize the ValueCondition into a JSON compatible object
  51949. * @returns serialization object
  51950. */
  51951. ValueCondition.prototype.serialize = function () {
  51952. return this._serialize({
  51953. name: "ValueCondition",
  51954. properties: [
  51955. BABYLON.Action._GetTargetProperty(this._target),
  51956. { name: "propertyPath", value: this.propertyPath },
  51957. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51958. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51959. ]
  51960. });
  51961. };
  51962. /**
  51963. * Gets the name of the conditional operator for the ValueCondition
  51964. * @param operator the conditional operator
  51965. * @returns the name
  51966. */
  51967. ValueCondition.GetOperatorName = function (operator) {
  51968. switch (operator) {
  51969. case ValueCondition._IsEqual: return "IsEqual";
  51970. case ValueCondition._IsDifferent: return "IsDifferent";
  51971. case ValueCondition._IsGreater: return "IsGreater";
  51972. case ValueCondition._IsLesser: return "IsLesser";
  51973. default: return "";
  51974. }
  51975. };
  51976. /**
  51977. * Internal only
  51978. * @hidden
  51979. */
  51980. ValueCondition._IsEqual = 0;
  51981. /**
  51982. * Internal only
  51983. * @hidden
  51984. */
  51985. ValueCondition._IsDifferent = 1;
  51986. /**
  51987. * Internal only
  51988. * @hidden
  51989. */
  51990. ValueCondition._IsGreater = 2;
  51991. /**
  51992. * Internal only
  51993. * @hidden
  51994. */
  51995. ValueCondition._IsLesser = 3;
  51996. return ValueCondition;
  51997. }(Condition));
  51998. BABYLON.ValueCondition = ValueCondition;
  51999. /**
  52000. * Defines a predicate condition as an extension of Condition
  52001. */
  52002. var PredicateCondition = /** @class */ (function (_super) {
  52003. __extends(PredicateCondition, _super);
  52004. /**
  52005. * Creates a new PredicateCondition
  52006. * @param actionManager manager for the action the condition applies to
  52007. * @param predicate defines the predicate function used to validate the condition
  52008. */
  52009. function PredicateCondition(actionManager,
  52010. /** defines the predicate function used to validate the condition */
  52011. predicate) {
  52012. var _this = _super.call(this, actionManager) || this;
  52013. _this.predicate = predicate;
  52014. return _this;
  52015. }
  52016. /**
  52017. * @returns the validity of the predicate condition
  52018. */
  52019. PredicateCondition.prototype.isValid = function () {
  52020. return this.predicate();
  52021. };
  52022. return PredicateCondition;
  52023. }(Condition));
  52024. BABYLON.PredicateCondition = PredicateCondition;
  52025. /**
  52026. * Defines a state condition as an extension of Condition
  52027. */
  52028. var StateCondition = /** @class */ (function (_super) {
  52029. __extends(StateCondition, _super);
  52030. /**
  52031. * Creates a new StateCondition
  52032. * @param actionManager manager for the action the condition applies to
  52033. * @param target of the condition
  52034. * @param value to compare with target state
  52035. */
  52036. function StateCondition(actionManager, target, value) {
  52037. var _this = _super.call(this, actionManager) || this;
  52038. _this.value = value;
  52039. _this._target = target;
  52040. return _this;
  52041. }
  52042. /**
  52043. * @returns the validity of the state
  52044. */
  52045. StateCondition.prototype.isValid = function () {
  52046. return this._target.state === this.value;
  52047. };
  52048. /**
  52049. * Serialize the StateCondition into a JSON compatible object
  52050. * @returns serialization object
  52051. */
  52052. StateCondition.prototype.serialize = function () {
  52053. return this._serialize({
  52054. name: "StateCondition",
  52055. properties: [
  52056. BABYLON.Action._GetTargetProperty(this._target),
  52057. { name: "value", value: this.value }
  52058. ]
  52059. });
  52060. };
  52061. return StateCondition;
  52062. }(Condition));
  52063. BABYLON.StateCondition = StateCondition;
  52064. })(BABYLON || (BABYLON = {}));
  52065. //# sourceMappingURL=babylon.condition.js.map
  52066. var BABYLON;
  52067. (function (BABYLON) {
  52068. /**
  52069. * The action to be carried out following a trigger
  52070. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52071. */
  52072. var Action = /** @class */ (function () {
  52073. /**
  52074. * Creates a new Action
  52075. * @param triggerOptions the trigger, with or without parameters, for the action
  52076. * @param condition an optional determinant of action
  52077. */
  52078. function Action(
  52079. /** the trigger, with or without parameters, for the action */
  52080. triggerOptions, condition) {
  52081. this.triggerOptions = triggerOptions;
  52082. /**
  52083. * An event triggered prior to action being executed.
  52084. */
  52085. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52086. if (triggerOptions.parameter) {
  52087. this.trigger = triggerOptions.trigger;
  52088. this._triggerParameter = triggerOptions.parameter;
  52089. }
  52090. else {
  52091. this.trigger = triggerOptions;
  52092. }
  52093. this._nextActiveAction = this;
  52094. this._condition = condition;
  52095. }
  52096. /**
  52097. * Internal only
  52098. * @hidden
  52099. */
  52100. Action.prototype._prepare = function () {
  52101. };
  52102. /**
  52103. * Gets the trigger parameters
  52104. * @returns the trigger parameters
  52105. */
  52106. Action.prototype.getTriggerParameter = function () {
  52107. return this._triggerParameter;
  52108. };
  52109. /**
  52110. * Internal only - executes current action event
  52111. * @hidden
  52112. */
  52113. Action.prototype._executeCurrent = function (evt) {
  52114. if (this._nextActiveAction._condition) {
  52115. var condition = this._nextActiveAction._condition;
  52116. var currentRenderId = this._actionManager.getScene().getRenderId();
  52117. // We cache the current evaluation for the current frame
  52118. if (condition._evaluationId === currentRenderId) {
  52119. if (!condition._currentResult) {
  52120. return;
  52121. }
  52122. }
  52123. else {
  52124. condition._evaluationId = currentRenderId;
  52125. if (!condition.isValid()) {
  52126. condition._currentResult = false;
  52127. return;
  52128. }
  52129. condition._currentResult = true;
  52130. }
  52131. }
  52132. this.onBeforeExecuteObservable.notifyObservers(this);
  52133. this._nextActiveAction.execute(evt);
  52134. this.skipToNextActiveAction();
  52135. };
  52136. /**
  52137. * Execute placeholder for child classes
  52138. * @param evt optional action event
  52139. */
  52140. Action.prototype.execute = function (evt) {
  52141. };
  52142. /**
  52143. * Skips to next active action
  52144. */
  52145. Action.prototype.skipToNextActiveAction = function () {
  52146. if (this._nextActiveAction._child) {
  52147. if (!this._nextActiveAction._child._actionManager) {
  52148. this._nextActiveAction._child._actionManager = this._actionManager;
  52149. }
  52150. this._nextActiveAction = this._nextActiveAction._child;
  52151. }
  52152. else {
  52153. this._nextActiveAction = this;
  52154. }
  52155. };
  52156. /**
  52157. * Adds action to chain of actions, may be a DoNothingAction
  52158. * @param action defines the next action to execute
  52159. * @returns The action passed in
  52160. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52161. */
  52162. Action.prototype.then = function (action) {
  52163. this._child = action;
  52164. action._actionManager = this._actionManager;
  52165. action._prepare();
  52166. return action;
  52167. };
  52168. /**
  52169. * Internal only
  52170. * @hidden
  52171. */
  52172. Action.prototype._getProperty = function (propertyPath) {
  52173. return this._actionManager._getProperty(propertyPath);
  52174. };
  52175. /**
  52176. * Internal only
  52177. * @hidden
  52178. */
  52179. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52180. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52181. };
  52182. /**
  52183. * Serialize placeholder for child classes
  52184. * @param parent of child
  52185. * @returns the serialized object
  52186. */
  52187. Action.prototype.serialize = function (parent) {
  52188. };
  52189. /**
  52190. * Internal only called by serialize
  52191. * @hidden
  52192. */
  52193. Action.prototype._serialize = function (serializedAction, parent) {
  52194. var serializationObject = {
  52195. type: 1,
  52196. children: [],
  52197. name: serializedAction.name,
  52198. properties: serializedAction.properties || []
  52199. };
  52200. // Serialize child
  52201. if (this._child) {
  52202. this._child.serialize(serializationObject);
  52203. }
  52204. // Check if "this" has a condition
  52205. if (this._condition) {
  52206. var serializedCondition = this._condition.serialize();
  52207. serializedCondition.children.push(serializationObject);
  52208. if (parent) {
  52209. parent.children.push(serializedCondition);
  52210. }
  52211. return serializedCondition;
  52212. }
  52213. if (parent) {
  52214. parent.children.push(serializationObject);
  52215. }
  52216. return serializationObject;
  52217. };
  52218. /**
  52219. * Internal only
  52220. * @hidden
  52221. */
  52222. Action._SerializeValueAsString = function (value) {
  52223. if (typeof value === "number") {
  52224. return value.toString();
  52225. }
  52226. if (typeof value === "boolean") {
  52227. return value ? "true" : "false";
  52228. }
  52229. if (value instanceof BABYLON.Vector2) {
  52230. return value.x + ", " + value.y;
  52231. }
  52232. if (value instanceof BABYLON.Vector3) {
  52233. return value.x + ", " + value.y + ", " + value.z;
  52234. }
  52235. if (value instanceof BABYLON.Color3) {
  52236. return value.r + ", " + value.g + ", " + value.b;
  52237. }
  52238. if (value instanceof BABYLON.Color4) {
  52239. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52240. }
  52241. return value; // string
  52242. };
  52243. /**
  52244. * Internal only
  52245. * @hidden
  52246. */
  52247. Action._GetTargetProperty = function (target) {
  52248. return {
  52249. name: "target",
  52250. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52251. : target instanceof BABYLON.Light ? "LightProperties"
  52252. : target instanceof BABYLON.Camera ? "CameraProperties"
  52253. : "SceneProperties",
  52254. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52255. };
  52256. };
  52257. return Action;
  52258. }());
  52259. BABYLON.Action = Action;
  52260. })(BABYLON || (BABYLON = {}));
  52261. //# sourceMappingURL=babylon.action.js.map
  52262. var BABYLON;
  52263. (function (BABYLON) {
  52264. /**
  52265. * ActionEvent is the event being sent when an action is triggered.
  52266. */
  52267. var ActionEvent = /** @class */ (function () {
  52268. /**
  52269. * Creates a new ActionEvent
  52270. * @param source The mesh or sprite that triggered the action
  52271. * @param pointerX The X mouse cursor position at the time of the event
  52272. * @param pointerY The Y mouse cursor position at the time of the event
  52273. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52274. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52275. * @param additionalData additional data for the event
  52276. */
  52277. function ActionEvent(
  52278. /** The mesh or sprite that triggered the action */
  52279. source,
  52280. /** The X mouse cursor position at the time of the event */
  52281. pointerX,
  52282. /** The Y mouse cursor position at the time of the event */
  52283. pointerY,
  52284. /** The mesh that is currently pointed at (can be null) */
  52285. meshUnderPointer,
  52286. /** the original (browser) event that triggered the ActionEvent */
  52287. sourceEvent,
  52288. /** additional data for the event */
  52289. additionalData) {
  52290. this.source = source;
  52291. this.pointerX = pointerX;
  52292. this.pointerY = pointerY;
  52293. this.meshUnderPointer = meshUnderPointer;
  52294. this.sourceEvent = sourceEvent;
  52295. this.additionalData = additionalData;
  52296. }
  52297. /**
  52298. * Helper function to auto-create an ActionEvent from a source mesh.
  52299. * @param source The source mesh that triggered the event
  52300. * @param evt The original (browser) event
  52301. * @param additionalData additional data for the event
  52302. * @returns the new ActionEvent
  52303. */
  52304. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52305. var scene = source.getScene();
  52306. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52307. };
  52308. /**
  52309. * Helper function to auto-create an ActionEvent from a source sprite
  52310. * @param source The source sprite that triggered the event
  52311. * @param scene Scene associated with the sprite
  52312. * @param evt The original (browser) event
  52313. * @param additionalData additional data for the event
  52314. * @returns the new ActionEvent
  52315. */
  52316. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52317. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52318. };
  52319. /**
  52320. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52321. * @param scene the scene where the event occurred
  52322. * @param evt The original (browser) event
  52323. * @returns the new ActionEvent
  52324. */
  52325. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52326. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52327. };
  52328. /**
  52329. * Helper function to auto-create an ActionEvent from a primitive
  52330. * @param prim defines the target primitive
  52331. * @param pointerPos defines the pointer position
  52332. * @param evt The original (browser) event
  52333. * @param additionalData additional data for the event
  52334. * @returns the new ActionEvent
  52335. */
  52336. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52337. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52338. };
  52339. return ActionEvent;
  52340. }());
  52341. BABYLON.ActionEvent = ActionEvent;
  52342. /**
  52343. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52344. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52345. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52346. */
  52347. var ActionManager = /** @class */ (function () {
  52348. /**
  52349. * Creates a new action manager
  52350. * @param scene defines the hosting scene
  52351. */
  52352. function ActionManager(scene) {
  52353. // Members
  52354. /** Gets the list of actions */
  52355. this.actions = new Array();
  52356. /** Gets the cursor to use when hovering items */
  52357. this.hoverCursor = '';
  52358. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52359. scene._actionManagers.push(this);
  52360. }
  52361. Object.defineProperty(ActionManager, "NothingTrigger", {
  52362. /**
  52363. * Nothing
  52364. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52365. */
  52366. get: function () {
  52367. return ActionManager._NothingTrigger;
  52368. },
  52369. enumerable: true,
  52370. configurable: true
  52371. });
  52372. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52373. /**
  52374. * On pick
  52375. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52376. */
  52377. get: function () {
  52378. return ActionManager._OnPickTrigger;
  52379. },
  52380. enumerable: true,
  52381. configurable: true
  52382. });
  52383. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52384. /**
  52385. * On left pick
  52386. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52387. */
  52388. get: function () {
  52389. return ActionManager._OnLeftPickTrigger;
  52390. },
  52391. enumerable: true,
  52392. configurable: true
  52393. });
  52394. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52395. /**
  52396. * On right pick
  52397. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52398. */
  52399. get: function () {
  52400. return ActionManager._OnRightPickTrigger;
  52401. },
  52402. enumerable: true,
  52403. configurable: true
  52404. });
  52405. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52406. /**
  52407. * On center pick
  52408. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52409. */
  52410. get: function () {
  52411. return ActionManager._OnCenterPickTrigger;
  52412. },
  52413. enumerable: true,
  52414. configurable: true
  52415. });
  52416. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52417. /**
  52418. * On pick down
  52419. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52420. */
  52421. get: function () {
  52422. return ActionManager._OnPickDownTrigger;
  52423. },
  52424. enumerable: true,
  52425. configurable: true
  52426. });
  52427. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52428. /**
  52429. * On double pick
  52430. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52431. */
  52432. get: function () {
  52433. return ActionManager._OnDoublePickTrigger;
  52434. },
  52435. enumerable: true,
  52436. configurable: true
  52437. });
  52438. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52439. /**
  52440. * On pick up
  52441. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52442. */
  52443. get: function () {
  52444. return ActionManager._OnPickUpTrigger;
  52445. },
  52446. enumerable: true,
  52447. configurable: true
  52448. });
  52449. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52450. /**
  52451. * On pick out.
  52452. * This trigger will only be raised if you also declared a OnPickDown
  52453. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52454. */
  52455. get: function () {
  52456. return ActionManager._OnPickOutTrigger;
  52457. },
  52458. enumerable: true,
  52459. configurable: true
  52460. });
  52461. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52462. /**
  52463. * On long press
  52464. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52465. */
  52466. get: function () {
  52467. return ActionManager._OnLongPressTrigger;
  52468. },
  52469. enumerable: true,
  52470. configurable: true
  52471. });
  52472. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52473. /**
  52474. * On pointer over
  52475. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52476. */
  52477. get: function () {
  52478. return ActionManager._OnPointerOverTrigger;
  52479. },
  52480. enumerable: true,
  52481. configurable: true
  52482. });
  52483. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52484. /**
  52485. * On pointer out
  52486. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52487. */
  52488. get: function () {
  52489. return ActionManager._OnPointerOutTrigger;
  52490. },
  52491. enumerable: true,
  52492. configurable: true
  52493. });
  52494. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52495. /**
  52496. * On every frame
  52497. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52498. */
  52499. get: function () {
  52500. return ActionManager._OnEveryFrameTrigger;
  52501. },
  52502. enumerable: true,
  52503. configurable: true
  52504. });
  52505. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52506. /**
  52507. * On intersection enter
  52508. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52509. */
  52510. get: function () {
  52511. return ActionManager._OnIntersectionEnterTrigger;
  52512. },
  52513. enumerable: true,
  52514. configurable: true
  52515. });
  52516. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52517. /**
  52518. * On intersection exit
  52519. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52520. */
  52521. get: function () {
  52522. return ActionManager._OnIntersectionExitTrigger;
  52523. },
  52524. enumerable: true,
  52525. configurable: true
  52526. });
  52527. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52528. /**
  52529. * On key down
  52530. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52531. */
  52532. get: function () {
  52533. return ActionManager._OnKeyDownTrigger;
  52534. },
  52535. enumerable: true,
  52536. configurable: true
  52537. });
  52538. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52539. /**
  52540. * On key up
  52541. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52542. */
  52543. get: function () {
  52544. return ActionManager._OnKeyUpTrigger;
  52545. },
  52546. enumerable: true,
  52547. configurable: true
  52548. });
  52549. // Methods
  52550. /**
  52551. * Releases all associated resources
  52552. */
  52553. ActionManager.prototype.dispose = function () {
  52554. var index = this._scene._actionManagers.indexOf(this);
  52555. for (var i = 0; i < this.actions.length; i++) {
  52556. var action = this.actions[i];
  52557. ActionManager.Triggers[action.trigger]--;
  52558. if (ActionManager.Triggers[action.trigger] === 0) {
  52559. delete ActionManager.Triggers[action.trigger];
  52560. }
  52561. }
  52562. if (index > -1) {
  52563. this._scene._actionManagers.splice(index, 1);
  52564. }
  52565. };
  52566. /**
  52567. * Gets hosting scene
  52568. * @returns the hosting scene
  52569. */
  52570. ActionManager.prototype.getScene = function () {
  52571. return this._scene;
  52572. };
  52573. /**
  52574. * Does this action manager handles actions of any of the given triggers
  52575. * @param triggers defines the triggers to be tested
  52576. * @return a boolean indicating whether one (or more) of the triggers is handled
  52577. */
  52578. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52579. for (var index = 0; index < this.actions.length; index++) {
  52580. var action = this.actions[index];
  52581. if (triggers.indexOf(action.trigger) > -1) {
  52582. return true;
  52583. }
  52584. }
  52585. return false;
  52586. };
  52587. /**
  52588. * Does this action manager handles actions of a given trigger
  52589. * @param trigger defines the trigger to be tested
  52590. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52591. * @return whether the trigger is handled
  52592. */
  52593. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52594. for (var index = 0; index < this.actions.length; index++) {
  52595. var action = this.actions[index];
  52596. if (action.trigger === trigger) {
  52597. if (parameterPredicate) {
  52598. if (parameterPredicate(action.getTriggerParameter())) {
  52599. return true;
  52600. }
  52601. }
  52602. else {
  52603. return true;
  52604. }
  52605. }
  52606. }
  52607. return false;
  52608. };
  52609. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52610. /**
  52611. * Does this action manager has pointer triggers
  52612. */
  52613. get: function () {
  52614. for (var index = 0; index < this.actions.length; index++) {
  52615. var action = this.actions[index];
  52616. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52617. return true;
  52618. }
  52619. }
  52620. return false;
  52621. },
  52622. enumerable: true,
  52623. configurable: true
  52624. });
  52625. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52626. /**
  52627. * Does this action manager has pick triggers
  52628. */
  52629. get: function () {
  52630. for (var index = 0; index < this.actions.length; index++) {
  52631. var action = this.actions[index];
  52632. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52633. return true;
  52634. }
  52635. }
  52636. return false;
  52637. },
  52638. enumerable: true,
  52639. configurable: true
  52640. });
  52641. Object.defineProperty(ActionManager, "HasTriggers", {
  52642. /**
  52643. * Does exist one action manager with at least one trigger
  52644. **/
  52645. get: function () {
  52646. for (var t in ActionManager.Triggers) {
  52647. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52648. return true;
  52649. }
  52650. }
  52651. return false;
  52652. },
  52653. enumerable: true,
  52654. configurable: true
  52655. });
  52656. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52657. /**
  52658. * Does exist one action manager with at least one pick trigger
  52659. **/
  52660. get: function () {
  52661. for (var t in ActionManager.Triggers) {
  52662. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52663. var t_int = parseInt(t);
  52664. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52665. return true;
  52666. }
  52667. }
  52668. }
  52669. return false;
  52670. },
  52671. enumerable: true,
  52672. configurable: true
  52673. });
  52674. /**
  52675. * Does exist one action manager that handles actions of a given trigger
  52676. * @param trigger defines the trigger to be tested
  52677. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52678. **/
  52679. ActionManager.HasSpecificTrigger = function (trigger) {
  52680. for (var t in ActionManager.Triggers) {
  52681. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52682. var t_int = parseInt(t);
  52683. if (t_int === trigger) {
  52684. return true;
  52685. }
  52686. }
  52687. }
  52688. return false;
  52689. };
  52690. /**
  52691. * Registers an action to this action manager
  52692. * @param action defines the action to be registered
  52693. * @return the action amended (prepared) after registration
  52694. */
  52695. ActionManager.prototype.registerAction = function (action) {
  52696. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52697. if (this.getScene().actionManager !== this) {
  52698. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52699. return null;
  52700. }
  52701. }
  52702. this.actions.push(action);
  52703. if (ActionManager.Triggers[action.trigger]) {
  52704. ActionManager.Triggers[action.trigger]++;
  52705. }
  52706. else {
  52707. ActionManager.Triggers[action.trigger] = 1;
  52708. }
  52709. action._actionManager = this;
  52710. action._prepare();
  52711. return action;
  52712. };
  52713. /**
  52714. * Unregisters an action to this action manager
  52715. * @param action defines the action to be unregistered
  52716. * @return a boolean indicating whether the action has been unregistered
  52717. */
  52718. ActionManager.prototype.unregisterAction = function (action) {
  52719. var index = this.actions.indexOf(action);
  52720. if (index !== -1) {
  52721. this.actions.splice(index, 1);
  52722. ActionManager.Triggers[action.trigger] -= 1;
  52723. if (ActionManager.Triggers[action.trigger] === 0) {
  52724. delete ActionManager.Triggers[action.trigger];
  52725. }
  52726. delete action._actionManager;
  52727. return true;
  52728. }
  52729. return false;
  52730. };
  52731. /**
  52732. * Process a specific trigger
  52733. * @param trigger defines the trigger to process
  52734. * @param evt defines the event details to be processed
  52735. */
  52736. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52737. for (var index = 0; index < this.actions.length; index++) {
  52738. var action = this.actions[index];
  52739. if (action.trigger === trigger) {
  52740. if (evt) {
  52741. if (trigger === ActionManager.OnKeyUpTrigger
  52742. || trigger === ActionManager.OnKeyDownTrigger) {
  52743. var parameter = action.getTriggerParameter();
  52744. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52745. if (!parameter.toLowerCase) {
  52746. continue;
  52747. }
  52748. var lowerCase = parameter.toLowerCase();
  52749. if (lowerCase !== evt.sourceEvent.key) {
  52750. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52751. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52752. if (actualkey !== lowerCase) {
  52753. continue;
  52754. }
  52755. }
  52756. }
  52757. }
  52758. }
  52759. action._executeCurrent(evt);
  52760. }
  52761. }
  52762. };
  52763. /** @hidden */
  52764. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52765. var properties = propertyPath.split(".");
  52766. for (var index = 0; index < properties.length - 1; index++) {
  52767. target = target[properties[index]];
  52768. }
  52769. return target;
  52770. };
  52771. /** @hidden */
  52772. ActionManager.prototype._getProperty = function (propertyPath) {
  52773. var properties = propertyPath.split(".");
  52774. return properties[properties.length - 1];
  52775. };
  52776. /**
  52777. * Serialize this manager to a JSON object
  52778. * @param name defines the property name to store this manager
  52779. * @returns a JSON representation of this manager
  52780. */
  52781. ActionManager.prototype.serialize = function (name) {
  52782. var root = {
  52783. children: new Array(),
  52784. name: name,
  52785. type: 3,
  52786. properties: new Array() // Empty for root but required
  52787. };
  52788. for (var i = 0; i < this.actions.length; i++) {
  52789. var triggerObject = {
  52790. type: 0,
  52791. children: new Array(),
  52792. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52793. properties: new Array()
  52794. };
  52795. var triggerOptions = this.actions[i].triggerOptions;
  52796. if (triggerOptions && typeof triggerOptions !== "number") {
  52797. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52798. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52799. }
  52800. else {
  52801. var parameter = {};
  52802. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52803. if (triggerOptions.parameter.mesh) {
  52804. parameter._meshId = triggerOptions.parameter.mesh.id;
  52805. }
  52806. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52807. }
  52808. }
  52809. // Serialize child action, recursively
  52810. this.actions[i].serialize(triggerObject);
  52811. // Add serialized trigger
  52812. root.children.push(triggerObject);
  52813. }
  52814. return root;
  52815. };
  52816. /**
  52817. * Creates a new ActionManager from a JSON data
  52818. * @param parsedActions defines the JSON data to read from
  52819. * @param object defines the hosting mesh
  52820. * @param scene defines the hosting scene
  52821. */
  52822. ActionManager.Parse = function (parsedActions, object, scene) {
  52823. var actionManager = new ActionManager(scene);
  52824. if (object === null)
  52825. scene.actionManager = actionManager;
  52826. else
  52827. object.actionManager = actionManager;
  52828. // instanciate a new object
  52829. var instanciate = function (name, params) {
  52830. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52831. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52832. newInstance.constructor.apply(newInstance, params);
  52833. return newInstance;
  52834. };
  52835. var parseParameter = function (name, value, target, propertyPath) {
  52836. if (propertyPath === null) {
  52837. // String, boolean or float
  52838. var floatValue = parseFloat(value);
  52839. if (value === "true" || value === "false")
  52840. return value === "true";
  52841. else
  52842. return isNaN(floatValue) ? value : floatValue;
  52843. }
  52844. var effectiveTarget = propertyPath.split(".");
  52845. var values = value.split(",");
  52846. // Get effective Target
  52847. for (var i = 0; i < effectiveTarget.length; i++) {
  52848. target = target[effectiveTarget[i]];
  52849. }
  52850. // Return appropriate value with its type
  52851. if (typeof (target) === "boolean")
  52852. return values[0] === "true";
  52853. if (typeof (target) === "string")
  52854. return values[0];
  52855. // Parameters with multiple values such as Vector3 etc.
  52856. var split = new Array();
  52857. for (var i = 0; i < values.length; i++)
  52858. split.push(parseFloat(values[i]));
  52859. if (target instanceof BABYLON.Vector3)
  52860. return BABYLON.Vector3.FromArray(split);
  52861. if (target instanceof BABYLON.Vector4)
  52862. return BABYLON.Vector4.FromArray(split);
  52863. if (target instanceof BABYLON.Color3)
  52864. return BABYLON.Color3.FromArray(split);
  52865. if (target instanceof BABYLON.Color4)
  52866. return BABYLON.Color4.FromArray(split);
  52867. return parseFloat(values[0]);
  52868. };
  52869. // traverse graph per trigger
  52870. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52871. if (combineArray === void 0) { combineArray = null; }
  52872. if (parsedAction.detached)
  52873. return;
  52874. var parameters = new Array();
  52875. var target = null;
  52876. var propertyPath = null;
  52877. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52878. // Parameters
  52879. if (parsedAction.type === 2)
  52880. parameters.push(actionManager);
  52881. else
  52882. parameters.push(trigger);
  52883. if (combine) {
  52884. var actions = new Array();
  52885. for (var j = 0; j < parsedAction.combine.length; j++) {
  52886. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52887. }
  52888. parameters.push(actions);
  52889. }
  52890. else {
  52891. for (var i = 0; i < parsedAction.properties.length; i++) {
  52892. var value = parsedAction.properties[i].value;
  52893. var name = parsedAction.properties[i].name;
  52894. var targetType = parsedAction.properties[i].targetType;
  52895. if (name === "target")
  52896. if (targetType !== null && targetType === "SceneProperties")
  52897. value = target = scene;
  52898. else
  52899. value = target = scene.getNodeByName(value);
  52900. else if (name === "parent")
  52901. value = scene.getNodeByName(value);
  52902. else if (name === "sound")
  52903. value = scene.getSoundByName(value);
  52904. else if (name !== "propertyPath") {
  52905. if (parsedAction.type === 2 && name === "operator")
  52906. value = BABYLON.ValueCondition[value];
  52907. else
  52908. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52909. }
  52910. else {
  52911. propertyPath = value;
  52912. }
  52913. parameters.push(value);
  52914. }
  52915. }
  52916. if (combineArray === null) {
  52917. parameters.push(condition);
  52918. }
  52919. else {
  52920. parameters.push(null);
  52921. }
  52922. // If interpolate value action
  52923. if (parsedAction.name === "InterpolateValueAction") {
  52924. var param = parameters[parameters.length - 2];
  52925. parameters[parameters.length - 1] = param;
  52926. parameters[parameters.length - 2] = condition;
  52927. }
  52928. // Action or condition(s) and not CombineAction
  52929. var newAction = instanciate(parsedAction.name, parameters);
  52930. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52931. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52932. if (action)
  52933. action.then(nothing);
  52934. else
  52935. actionManager.registerAction(nothing);
  52936. action = nothing;
  52937. }
  52938. if (combineArray === null) {
  52939. if (newAction instanceof BABYLON.Condition) {
  52940. condition = newAction;
  52941. newAction = action;
  52942. }
  52943. else {
  52944. condition = null;
  52945. if (action)
  52946. action.then(newAction);
  52947. else
  52948. actionManager.registerAction(newAction);
  52949. }
  52950. }
  52951. else {
  52952. combineArray.push(newAction);
  52953. }
  52954. for (var i = 0; i < parsedAction.children.length; i++)
  52955. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52956. };
  52957. // triggers
  52958. for (var i = 0; i < parsedActions.children.length; i++) {
  52959. var triggerParams;
  52960. var trigger = parsedActions.children[i];
  52961. if (trigger.properties.length > 0) {
  52962. var param = trigger.properties[0].value;
  52963. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52964. if (value._meshId) {
  52965. value.mesh = scene.getMeshByID(value._meshId);
  52966. }
  52967. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52968. }
  52969. else
  52970. triggerParams = ActionManager[trigger.name];
  52971. for (var j = 0; j < trigger.children.length; j++) {
  52972. if (!trigger.detached)
  52973. traverse(trigger.children[j], triggerParams, null, null);
  52974. }
  52975. }
  52976. };
  52977. /**
  52978. * Get a trigger name by index
  52979. * @param trigger defines the trigger index
  52980. * @returns a trigger name
  52981. */
  52982. ActionManager.GetTriggerName = function (trigger) {
  52983. switch (trigger) {
  52984. case 0: return "NothingTrigger";
  52985. case 1: return "OnPickTrigger";
  52986. case 2: return "OnLeftPickTrigger";
  52987. case 3: return "OnRightPickTrigger";
  52988. case 4: return "OnCenterPickTrigger";
  52989. case 5: return "OnPickDownTrigger";
  52990. case 6: return "OnPickUpTrigger";
  52991. case 7: return "OnLongPressTrigger";
  52992. case 8: return "OnPointerOverTrigger";
  52993. case 9: return "OnPointerOutTrigger";
  52994. case 10: return "OnEveryFrameTrigger";
  52995. case 11: return "OnIntersectionEnterTrigger";
  52996. case 12: return "OnIntersectionExitTrigger";
  52997. case 13: return "OnKeyDownTrigger";
  52998. case 14: return "OnKeyUpTrigger";
  52999. case 15: return "OnPickOutTrigger";
  53000. default: return "";
  53001. }
  53002. };
  53003. // Statics
  53004. ActionManager._NothingTrigger = 0;
  53005. ActionManager._OnPickTrigger = 1;
  53006. ActionManager._OnLeftPickTrigger = 2;
  53007. ActionManager._OnRightPickTrigger = 3;
  53008. ActionManager._OnCenterPickTrigger = 4;
  53009. ActionManager._OnPickDownTrigger = 5;
  53010. ActionManager._OnDoublePickTrigger = 6;
  53011. ActionManager._OnPickUpTrigger = 7;
  53012. ActionManager._OnLongPressTrigger = 8;
  53013. ActionManager._OnPointerOverTrigger = 9;
  53014. ActionManager._OnPointerOutTrigger = 10;
  53015. ActionManager._OnEveryFrameTrigger = 11;
  53016. ActionManager._OnIntersectionEnterTrigger = 12;
  53017. ActionManager._OnIntersectionExitTrigger = 13;
  53018. ActionManager._OnKeyDownTrigger = 14;
  53019. ActionManager._OnKeyUpTrigger = 15;
  53020. ActionManager._OnPickOutTrigger = 16;
  53021. /** Gets the list of active triggers */
  53022. ActionManager.Triggers = {};
  53023. return ActionManager;
  53024. }());
  53025. BABYLON.ActionManager = ActionManager;
  53026. })(BABYLON || (BABYLON = {}));
  53027. //# sourceMappingURL=babylon.actionManager.js.map
  53028. var BABYLON;
  53029. (function (BABYLON) {
  53030. var InterpolateValueAction = /** @class */ (function (_super) {
  53031. __extends(InterpolateValueAction, _super);
  53032. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53033. if (duration === void 0) { duration = 1000; }
  53034. var _this = _super.call(this, triggerOptions, condition) || this;
  53035. _this.propertyPath = propertyPath;
  53036. _this.value = value;
  53037. _this.duration = duration;
  53038. _this.stopOtherAnimations = stopOtherAnimations;
  53039. _this.onInterpolationDone = onInterpolationDone;
  53040. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53041. _this._target = _this._effectiveTarget = target;
  53042. return _this;
  53043. }
  53044. InterpolateValueAction.prototype._prepare = function () {
  53045. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53046. this._property = this._getProperty(this.propertyPath);
  53047. };
  53048. InterpolateValueAction.prototype.execute = function () {
  53049. var _this = this;
  53050. var scene = this._actionManager.getScene();
  53051. var keys = [
  53052. {
  53053. frame: 0,
  53054. value: this._effectiveTarget[this._property]
  53055. }, {
  53056. frame: 100,
  53057. value: this.value
  53058. }
  53059. ];
  53060. var dataType;
  53061. if (typeof this.value === "number") {
  53062. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53063. }
  53064. else if (this.value instanceof BABYLON.Color3) {
  53065. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53066. }
  53067. else if (this.value instanceof BABYLON.Vector3) {
  53068. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53069. }
  53070. else if (this.value instanceof BABYLON.Matrix) {
  53071. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53072. }
  53073. else if (this.value instanceof BABYLON.Quaternion) {
  53074. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53075. }
  53076. else {
  53077. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53078. return;
  53079. }
  53080. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53081. animation.setKeys(keys);
  53082. if (this.stopOtherAnimations) {
  53083. scene.stopAnimation(this._effectiveTarget);
  53084. }
  53085. var wrapper = function () {
  53086. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53087. if (_this.onInterpolationDone) {
  53088. _this.onInterpolationDone();
  53089. }
  53090. };
  53091. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53092. };
  53093. InterpolateValueAction.prototype.serialize = function (parent) {
  53094. return _super.prototype._serialize.call(this, {
  53095. name: "InterpolateValueAction",
  53096. properties: [
  53097. BABYLON.Action._GetTargetProperty(this._target),
  53098. { name: "propertyPath", value: this.propertyPath },
  53099. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53100. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53101. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53102. ]
  53103. }, parent);
  53104. };
  53105. return InterpolateValueAction;
  53106. }(BABYLON.Action));
  53107. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53108. })(BABYLON || (BABYLON = {}));
  53109. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53110. var BABYLON;
  53111. (function (BABYLON) {
  53112. var SwitchBooleanAction = /** @class */ (function (_super) {
  53113. __extends(SwitchBooleanAction, _super);
  53114. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53115. var _this = _super.call(this, triggerOptions, condition) || this;
  53116. _this.propertyPath = propertyPath;
  53117. _this._target = _this._effectiveTarget = target;
  53118. return _this;
  53119. }
  53120. SwitchBooleanAction.prototype._prepare = function () {
  53121. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53122. this._property = this._getProperty(this.propertyPath);
  53123. };
  53124. SwitchBooleanAction.prototype.execute = function () {
  53125. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53126. };
  53127. SwitchBooleanAction.prototype.serialize = function (parent) {
  53128. return _super.prototype._serialize.call(this, {
  53129. name: "SwitchBooleanAction",
  53130. properties: [
  53131. BABYLON.Action._GetTargetProperty(this._target),
  53132. { name: "propertyPath", value: this.propertyPath }
  53133. ]
  53134. }, parent);
  53135. };
  53136. return SwitchBooleanAction;
  53137. }(BABYLON.Action));
  53138. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53139. var SetStateAction = /** @class */ (function (_super) {
  53140. __extends(SetStateAction, _super);
  53141. function SetStateAction(triggerOptions, target, value, condition) {
  53142. var _this = _super.call(this, triggerOptions, condition) || this;
  53143. _this.value = value;
  53144. _this._target = target;
  53145. return _this;
  53146. }
  53147. SetStateAction.prototype.execute = function () {
  53148. this._target.state = this.value;
  53149. };
  53150. SetStateAction.prototype.serialize = function (parent) {
  53151. return _super.prototype._serialize.call(this, {
  53152. name: "SetStateAction",
  53153. properties: [
  53154. BABYLON.Action._GetTargetProperty(this._target),
  53155. { name: "value", value: this.value }
  53156. ]
  53157. }, parent);
  53158. };
  53159. return SetStateAction;
  53160. }(BABYLON.Action));
  53161. BABYLON.SetStateAction = SetStateAction;
  53162. var SetValueAction = /** @class */ (function (_super) {
  53163. __extends(SetValueAction, _super);
  53164. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53165. var _this = _super.call(this, triggerOptions, condition) || this;
  53166. _this.propertyPath = propertyPath;
  53167. _this.value = value;
  53168. _this._target = _this._effectiveTarget = target;
  53169. return _this;
  53170. }
  53171. SetValueAction.prototype._prepare = function () {
  53172. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53173. this._property = this._getProperty(this.propertyPath);
  53174. };
  53175. SetValueAction.prototype.execute = function () {
  53176. this._effectiveTarget[this._property] = this.value;
  53177. if (this._target.markAsDirty) {
  53178. this._target.markAsDirty(this._property);
  53179. }
  53180. };
  53181. SetValueAction.prototype.serialize = function (parent) {
  53182. return _super.prototype._serialize.call(this, {
  53183. name: "SetValueAction",
  53184. properties: [
  53185. BABYLON.Action._GetTargetProperty(this._target),
  53186. { name: "propertyPath", value: this.propertyPath },
  53187. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53188. ]
  53189. }, parent);
  53190. };
  53191. return SetValueAction;
  53192. }(BABYLON.Action));
  53193. BABYLON.SetValueAction = SetValueAction;
  53194. var IncrementValueAction = /** @class */ (function (_super) {
  53195. __extends(IncrementValueAction, _super);
  53196. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53197. var _this = _super.call(this, triggerOptions, condition) || this;
  53198. _this.propertyPath = propertyPath;
  53199. _this.value = value;
  53200. _this._target = _this._effectiveTarget = target;
  53201. return _this;
  53202. }
  53203. IncrementValueAction.prototype._prepare = function () {
  53204. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53205. this._property = this._getProperty(this.propertyPath);
  53206. if (typeof this._effectiveTarget[this._property] !== "number") {
  53207. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53208. }
  53209. };
  53210. IncrementValueAction.prototype.execute = function () {
  53211. this._effectiveTarget[this._property] += this.value;
  53212. if (this._target.markAsDirty) {
  53213. this._target.markAsDirty(this._property);
  53214. }
  53215. };
  53216. IncrementValueAction.prototype.serialize = function (parent) {
  53217. return _super.prototype._serialize.call(this, {
  53218. name: "IncrementValueAction",
  53219. properties: [
  53220. BABYLON.Action._GetTargetProperty(this._target),
  53221. { name: "propertyPath", value: this.propertyPath },
  53222. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53223. ]
  53224. }, parent);
  53225. };
  53226. return IncrementValueAction;
  53227. }(BABYLON.Action));
  53228. BABYLON.IncrementValueAction = IncrementValueAction;
  53229. var PlayAnimationAction = /** @class */ (function (_super) {
  53230. __extends(PlayAnimationAction, _super);
  53231. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53232. var _this = _super.call(this, triggerOptions, condition) || this;
  53233. _this.from = from;
  53234. _this.to = to;
  53235. _this.loop = loop;
  53236. _this._target = target;
  53237. return _this;
  53238. }
  53239. PlayAnimationAction.prototype._prepare = function () {
  53240. };
  53241. PlayAnimationAction.prototype.execute = function () {
  53242. var scene = this._actionManager.getScene();
  53243. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53244. };
  53245. PlayAnimationAction.prototype.serialize = function (parent) {
  53246. return _super.prototype._serialize.call(this, {
  53247. name: "PlayAnimationAction",
  53248. properties: [
  53249. BABYLON.Action._GetTargetProperty(this._target),
  53250. { name: "from", value: String(this.from) },
  53251. { name: "to", value: String(this.to) },
  53252. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53253. ]
  53254. }, parent);
  53255. };
  53256. return PlayAnimationAction;
  53257. }(BABYLON.Action));
  53258. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53259. var StopAnimationAction = /** @class */ (function (_super) {
  53260. __extends(StopAnimationAction, _super);
  53261. function StopAnimationAction(triggerOptions, target, condition) {
  53262. var _this = _super.call(this, triggerOptions, condition) || this;
  53263. _this._target = target;
  53264. return _this;
  53265. }
  53266. StopAnimationAction.prototype._prepare = function () {
  53267. };
  53268. StopAnimationAction.prototype.execute = function () {
  53269. var scene = this._actionManager.getScene();
  53270. scene.stopAnimation(this._target);
  53271. };
  53272. StopAnimationAction.prototype.serialize = function (parent) {
  53273. return _super.prototype._serialize.call(this, {
  53274. name: "StopAnimationAction",
  53275. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53276. }, parent);
  53277. };
  53278. return StopAnimationAction;
  53279. }(BABYLON.Action));
  53280. BABYLON.StopAnimationAction = StopAnimationAction;
  53281. var DoNothingAction = /** @class */ (function (_super) {
  53282. __extends(DoNothingAction, _super);
  53283. function DoNothingAction(triggerOptions, condition) {
  53284. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53285. return _super.call(this, triggerOptions, condition) || this;
  53286. }
  53287. DoNothingAction.prototype.execute = function () {
  53288. };
  53289. DoNothingAction.prototype.serialize = function (parent) {
  53290. return _super.prototype._serialize.call(this, {
  53291. name: "DoNothingAction",
  53292. properties: []
  53293. }, parent);
  53294. };
  53295. return DoNothingAction;
  53296. }(BABYLON.Action));
  53297. BABYLON.DoNothingAction = DoNothingAction;
  53298. var CombineAction = /** @class */ (function (_super) {
  53299. __extends(CombineAction, _super);
  53300. function CombineAction(triggerOptions, children, condition) {
  53301. var _this = _super.call(this, triggerOptions, condition) || this;
  53302. _this.children = children;
  53303. return _this;
  53304. }
  53305. CombineAction.prototype._prepare = function () {
  53306. for (var index = 0; index < this.children.length; index++) {
  53307. this.children[index]._actionManager = this._actionManager;
  53308. this.children[index]._prepare();
  53309. }
  53310. };
  53311. CombineAction.prototype.execute = function (evt) {
  53312. for (var index = 0; index < this.children.length; index++) {
  53313. this.children[index].execute(evt);
  53314. }
  53315. };
  53316. CombineAction.prototype.serialize = function (parent) {
  53317. var serializationObject = _super.prototype._serialize.call(this, {
  53318. name: "CombineAction",
  53319. properties: [],
  53320. combine: []
  53321. }, parent);
  53322. for (var i = 0; i < this.children.length; i++) {
  53323. serializationObject.combine.push(this.children[i].serialize(null));
  53324. }
  53325. return serializationObject;
  53326. };
  53327. return CombineAction;
  53328. }(BABYLON.Action));
  53329. BABYLON.CombineAction = CombineAction;
  53330. var ExecuteCodeAction = /** @class */ (function (_super) {
  53331. __extends(ExecuteCodeAction, _super);
  53332. function ExecuteCodeAction(triggerOptions, func, condition) {
  53333. var _this = _super.call(this, triggerOptions, condition) || this;
  53334. _this.func = func;
  53335. return _this;
  53336. }
  53337. ExecuteCodeAction.prototype.execute = function (evt) {
  53338. this.func(evt);
  53339. };
  53340. return ExecuteCodeAction;
  53341. }(BABYLON.Action));
  53342. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53343. var SetParentAction = /** @class */ (function (_super) {
  53344. __extends(SetParentAction, _super);
  53345. function SetParentAction(triggerOptions, target, parent, condition) {
  53346. var _this = _super.call(this, triggerOptions, condition) || this;
  53347. _this._target = target;
  53348. _this._parent = parent;
  53349. return _this;
  53350. }
  53351. SetParentAction.prototype._prepare = function () {
  53352. };
  53353. SetParentAction.prototype.execute = function () {
  53354. if (this._target.parent === this._parent) {
  53355. return;
  53356. }
  53357. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53358. invertParentWorldMatrix.invert();
  53359. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53360. this._target.parent = this._parent;
  53361. };
  53362. SetParentAction.prototype.serialize = function (parent) {
  53363. return _super.prototype._serialize.call(this, {
  53364. name: "SetParentAction",
  53365. properties: [
  53366. BABYLON.Action._GetTargetProperty(this._target),
  53367. BABYLON.Action._GetTargetProperty(this._parent),
  53368. ]
  53369. }, parent);
  53370. };
  53371. return SetParentAction;
  53372. }(BABYLON.Action));
  53373. BABYLON.SetParentAction = SetParentAction;
  53374. var PlaySoundAction = /** @class */ (function (_super) {
  53375. __extends(PlaySoundAction, _super);
  53376. function PlaySoundAction(triggerOptions, sound, condition) {
  53377. var _this = _super.call(this, triggerOptions, condition) || this;
  53378. _this._sound = sound;
  53379. return _this;
  53380. }
  53381. PlaySoundAction.prototype._prepare = function () {
  53382. };
  53383. PlaySoundAction.prototype.execute = function () {
  53384. if (this._sound !== undefined)
  53385. this._sound.play();
  53386. };
  53387. PlaySoundAction.prototype.serialize = function (parent) {
  53388. return _super.prototype._serialize.call(this, {
  53389. name: "PlaySoundAction",
  53390. properties: [{ name: "sound", value: this._sound.name }]
  53391. }, parent);
  53392. };
  53393. return PlaySoundAction;
  53394. }(BABYLON.Action));
  53395. BABYLON.PlaySoundAction = PlaySoundAction;
  53396. var StopSoundAction = /** @class */ (function (_super) {
  53397. __extends(StopSoundAction, _super);
  53398. function StopSoundAction(triggerOptions, sound, condition) {
  53399. var _this = _super.call(this, triggerOptions, condition) || this;
  53400. _this._sound = sound;
  53401. return _this;
  53402. }
  53403. StopSoundAction.prototype._prepare = function () {
  53404. };
  53405. StopSoundAction.prototype.execute = function () {
  53406. if (this._sound !== undefined)
  53407. this._sound.stop();
  53408. };
  53409. StopSoundAction.prototype.serialize = function (parent) {
  53410. return _super.prototype._serialize.call(this, {
  53411. name: "StopSoundAction",
  53412. properties: [{ name: "sound", value: this._sound.name }]
  53413. }, parent);
  53414. };
  53415. return StopSoundAction;
  53416. }(BABYLON.Action));
  53417. BABYLON.StopSoundAction = StopSoundAction;
  53418. })(BABYLON || (BABYLON = {}));
  53419. //# sourceMappingURL=babylon.directActions.js.map
  53420. var BABYLON;
  53421. (function (BABYLON) {
  53422. var SpriteManager = /** @class */ (function () {
  53423. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53424. if (epsilon === void 0) { epsilon = 0.01; }
  53425. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53426. this.name = name;
  53427. this.sprites = new Array();
  53428. this.renderingGroupId = 0;
  53429. this.layerMask = 0x0FFFFFFF;
  53430. this.fogEnabled = true;
  53431. this.isPickable = false;
  53432. /**
  53433. * An event triggered when the manager is disposed.
  53434. */
  53435. this.onDisposeObservable = new BABYLON.Observable();
  53436. this._vertexBuffers = {};
  53437. this._capacity = capacity;
  53438. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53439. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53440. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53441. if (cellSize.width && cellSize.height) {
  53442. this.cellWidth = cellSize.width;
  53443. this.cellHeight = cellSize.height;
  53444. }
  53445. else if (cellSize !== undefined) {
  53446. this.cellWidth = cellSize;
  53447. this.cellHeight = cellSize;
  53448. }
  53449. else {
  53450. return;
  53451. }
  53452. this._epsilon = epsilon;
  53453. this._scene = scene;
  53454. this._scene.spriteManagers.push(this);
  53455. var indices = [];
  53456. var index = 0;
  53457. for (var count = 0; count < capacity; count++) {
  53458. indices.push(index);
  53459. indices.push(index + 1);
  53460. indices.push(index + 2);
  53461. indices.push(index);
  53462. indices.push(index + 2);
  53463. indices.push(index + 3);
  53464. index += 4;
  53465. }
  53466. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53467. // VBO
  53468. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53469. this._vertexData = new Float32Array(capacity * 16 * 4);
  53470. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53471. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53472. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53473. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53474. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53475. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53476. this._vertexBuffers["options"] = options;
  53477. this._vertexBuffers["cellInfo"] = cellInfo;
  53478. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53479. // Effects
  53480. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53481. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53482. }
  53483. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53484. set: function (callback) {
  53485. if (this._onDisposeObserver) {
  53486. this.onDisposeObservable.remove(this._onDisposeObserver);
  53487. }
  53488. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53489. },
  53490. enumerable: true,
  53491. configurable: true
  53492. });
  53493. Object.defineProperty(SpriteManager.prototype, "texture", {
  53494. get: function () {
  53495. return this._spriteTexture;
  53496. },
  53497. set: function (value) {
  53498. this._spriteTexture = value;
  53499. },
  53500. enumerable: true,
  53501. configurable: true
  53502. });
  53503. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53504. var arrayOffset = index * 16;
  53505. if (offsetX === 0)
  53506. offsetX = this._epsilon;
  53507. else if (offsetX === 1)
  53508. offsetX = 1 - this._epsilon;
  53509. if (offsetY === 0)
  53510. offsetY = this._epsilon;
  53511. else if (offsetY === 1)
  53512. offsetY = 1 - this._epsilon;
  53513. this._vertexData[arrayOffset] = sprite.position.x;
  53514. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53515. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53516. this._vertexData[arrayOffset + 3] = sprite.angle;
  53517. this._vertexData[arrayOffset + 4] = sprite.width;
  53518. this._vertexData[arrayOffset + 5] = sprite.height;
  53519. this._vertexData[arrayOffset + 6] = offsetX;
  53520. this._vertexData[arrayOffset + 7] = offsetY;
  53521. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53522. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53523. var offset = (sprite.cellIndex / rowSize) >> 0;
  53524. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53525. this._vertexData[arrayOffset + 11] = offset;
  53526. // Color
  53527. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53528. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53529. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53530. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53531. };
  53532. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53533. var count = Math.min(this._capacity, this.sprites.length);
  53534. var min = BABYLON.Vector3.Zero();
  53535. var max = BABYLON.Vector3.Zero();
  53536. var distance = Number.MAX_VALUE;
  53537. var currentSprite = null;
  53538. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53539. var cameraView = camera.getViewMatrix();
  53540. for (var index = 0; index < count; index++) {
  53541. var sprite = this.sprites[index];
  53542. if (!sprite) {
  53543. continue;
  53544. }
  53545. if (predicate) {
  53546. if (!predicate(sprite)) {
  53547. continue;
  53548. }
  53549. }
  53550. else if (!sprite.isPickable) {
  53551. continue;
  53552. }
  53553. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53554. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53555. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53556. if (ray.intersectsBoxMinMax(min, max)) {
  53557. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53558. if (distance > currentDistance) {
  53559. distance = currentDistance;
  53560. currentSprite = sprite;
  53561. if (fastCheck) {
  53562. break;
  53563. }
  53564. }
  53565. }
  53566. }
  53567. if (currentSprite) {
  53568. var result = new BABYLON.PickingInfo();
  53569. result.hit = true;
  53570. result.pickedSprite = currentSprite;
  53571. result.distance = distance;
  53572. return result;
  53573. }
  53574. return null;
  53575. };
  53576. SpriteManager.prototype.render = function () {
  53577. // Check
  53578. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53579. return;
  53580. var engine = this._scene.getEngine();
  53581. var baseSize = this._spriteTexture.getBaseSize();
  53582. // Sprites
  53583. var deltaTime = engine.getDeltaTime();
  53584. var max = Math.min(this._capacity, this.sprites.length);
  53585. var rowSize = baseSize.width / this.cellWidth;
  53586. var offset = 0;
  53587. for (var index = 0; index < max; index++) {
  53588. var sprite = this.sprites[index];
  53589. if (!sprite || !sprite.isVisible) {
  53590. continue;
  53591. }
  53592. sprite._animate(deltaTime);
  53593. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53594. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53595. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53596. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53597. }
  53598. this._buffer.update(this._vertexData);
  53599. // Render
  53600. var effect = this._effectBase;
  53601. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53602. effect = this._effectFog;
  53603. }
  53604. engine.enableEffect(effect);
  53605. var viewMatrix = this._scene.getViewMatrix();
  53606. effect.setTexture("diffuseSampler", this._spriteTexture);
  53607. effect.setMatrix("view", viewMatrix);
  53608. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53609. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53610. // Fog
  53611. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53612. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53613. effect.setColor3("vFogColor", this._scene.fogColor);
  53614. }
  53615. // VBOs
  53616. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53617. // Draw order
  53618. engine.setDepthFunctionToLessOrEqual();
  53619. effect.setBool("alphaTest", true);
  53620. engine.setColorWrite(false);
  53621. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53622. engine.setColorWrite(true);
  53623. effect.setBool("alphaTest", false);
  53624. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53625. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53626. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53627. };
  53628. SpriteManager.prototype.dispose = function () {
  53629. if (this._buffer) {
  53630. this._buffer.dispose();
  53631. this._buffer = null;
  53632. }
  53633. if (this._indexBuffer) {
  53634. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53635. this._indexBuffer = null;
  53636. }
  53637. if (this._spriteTexture) {
  53638. this._spriteTexture.dispose();
  53639. this._spriteTexture = null;
  53640. }
  53641. // Remove from scene
  53642. var index = this._scene.spriteManagers.indexOf(this);
  53643. this._scene.spriteManagers.splice(index, 1);
  53644. // Callback
  53645. this.onDisposeObservable.notifyObservers(this);
  53646. this.onDisposeObservable.clear();
  53647. };
  53648. return SpriteManager;
  53649. }());
  53650. BABYLON.SpriteManager = SpriteManager;
  53651. })(BABYLON || (BABYLON = {}));
  53652. //# sourceMappingURL=babylon.spriteManager.js.map
  53653. var BABYLON;
  53654. (function (BABYLON) {
  53655. var Sprite = /** @class */ (function () {
  53656. function Sprite(name, manager) {
  53657. this.name = name;
  53658. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53659. this.width = 1.0;
  53660. this.height = 1.0;
  53661. this.angle = 0;
  53662. this.cellIndex = 0;
  53663. this.invertU = 0;
  53664. this.invertV = 0;
  53665. this.animations = new Array();
  53666. this.isPickable = false;
  53667. this._animationStarted = false;
  53668. this._loopAnimation = false;
  53669. this._fromIndex = 0;
  53670. this._toIndex = 0;
  53671. this._delay = 0;
  53672. this._direction = 1;
  53673. this._time = 0;
  53674. /**
  53675. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53676. */
  53677. this.isVisible = true;
  53678. this._manager = manager;
  53679. this._manager.sprites.push(this);
  53680. this.position = BABYLON.Vector3.Zero();
  53681. }
  53682. Object.defineProperty(Sprite.prototype, "size", {
  53683. get: function () {
  53684. return this.width;
  53685. },
  53686. set: function (value) {
  53687. this.width = value;
  53688. this.height = value;
  53689. },
  53690. enumerable: true,
  53691. configurable: true
  53692. });
  53693. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53694. this._fromIndex = from;
  53695. this._toIndex = to;
  53696. this._loopAnimation = loop;
  53697. this._delay = delay;
  53698. this._animationStarted = true;
  53699. this._direction = from < to ? 1 : -1;
  53700. this.cellIndex = from;
  53701. this._time = 0;
  53702. this._onAnimationEnd = onAnimationEnd;
  53703. };
  53704. Sprite.prototype.stopAnimation = function () {
  53705. this._animationStarted = false;
  53706. };
  53707. Sprite.prototype._animate = function (deltaTime) {
  53708. if (!this._animationStarted)
  53709. return;
  53710. this._time += deltaTime;
  53711. if (this._time > this._delay) {
  53712. this._time = this._time % this._delay;
  53713. this.cellIndex += this._direction;
  53714. if (this.cellIndex > this._toIndex) {
  53715. if (this._loopAnimation) {
  53716. this.cellIndex = this._fromIndex;
  53717. }
  53718. else {
  53719. this.cellIndex = this._toIndex;
  53720. this._animationStarted = false;
  53721. if (this._onAnimationEnd) {
  53722. this._onAnimationEnd();
  53723. }
  53724. if (this.disposeWhenFinishedAnimating) {
  53725. this.dispose();
  53726. }
  53727. }
  53728. }
  53729. }
  53730. };
  53731. Sprite.prototype.dispose = function () {
  53732. for (var i = 0; i < this._manager.sprites.length; i++) {
  53733. if (this._manager.sprites[i] == this) {
  53734. this._manager.sprites.splice(i, 1);
  53735. }
  53736. }
  53737. };
  53738. return Sprite;
  53739. }());
  53740. BABYLON.Sprite = Sprite;
  53741. })(BABYLON || (BABYLON = {}));
  53742. //# sourceMappingURL=babylon.sprite.js.map
  53743. var BABYLON;
  53744. (function (BABYLON) {
  53745. var IntersectionInfo = /** @class */ (function () {
  53746. function IntersectionInfo(bu, bv, distance) {
  53747. this.bu = bu;
  53748. this.bv = bv;
  53749. this.distance = distance;
  53750. this.faceId = 0;
  53751. this.subMeshId = 0;
  53752. }
  53753. return IntersectionInfo;
  53754. }());
  53755. BABYLON.IntersectionInfo = IntersectionInfo;
  53756. /**
  53757. * Information about the result of picking within a scene
  53758. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53759. */
  53760. var PickingInfo = /** @class */ (function () {
  53761. function PickingInfo() {
  53762. /**
  53763. * If the pick collided with an object
  53764. */
  53765. this.hit = false;
  53766. /**
  53767. * Distance away where the pick collided
  53768. */
  53769. this.distance = 0;
  53770. /**
  53771. * The location of pick collision
  53772. */
  53773. this.pickedPoint = null;
  53774. /**
  53775. * The mesh corrisponding the the pick collision
  53776. */
  53777. this.pickedMesh = null;
  53778. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53779. this.bu = 0;
  53780. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53781. this.bv = 0;
  53782. /** The id of the face on the mesh that was picked */
  53783. this.faceId = -1;
  53784. /** Id of the the submesh that was picked */
  53785. this.subMeshId = 0;
  53786. /** If a sprite was picked, this will be the sprite the pick collided with */
  53787. this.pickedSprite = null;
  53788. /**
  53789. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53790. */
  53791. this.originMesh = null;
  53792. /**
  53793. * The ray that was used to perform the picking.
  53794. */
  53795. this.ray = null;
  53796. }
  53797. /**
  53798. * Gets the normal corrispodning to the face the pick collided with
  53799. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53800. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53801. * @returns The normal corrispodning to the face the pick collided with
  53802. */
  53803. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53804. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53805. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53806. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53807. return null;
  53808. }
  53809. var indices = this.pickedMesh.getIndices();
  53810. if (!indices) {
  53811. return null;
  53812. }
  53813. var result;
  53814. if (useVerticesNormals) {
  53815. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53816. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53817. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53818. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53819. normal0 = normal0.scale(this.bu);
  53820. normal1 = normal1.scale(this.bv);
  53821. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53822. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53823. }
  53824. else {
  53825. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53826. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53827. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53828. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53829. var p1p2 = vertex1.subtract(vertex2);
  53830. var p3p2 = vertex3.subtract(vertex2);
  53831. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53832. }
  53833. if (useWorldCoordinates) {
  53834. var wm = this.pickedMesh.getWorldMatrix();
  53835. if (this.pickedMesh.nonUniformScaling) {
  53836. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53837. wm = BABYLON.Tmp.Matrix[0];
  53838. wm.setTranslationFromFloats(0, 0, 0);
  53839. wm.invert();
  53840. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53841. wm = BABYLON.Tmp.Matrix[1];
  53842. }
  53843. result = BABYLON.Vector3.TransformNormal(result, wm);
  53844. }
  53845. result.normalize();
  53846. return result;
  53847. };
  53848. /**
  53849. * Gets the texture coordinates of where the pick occured
  53850. * @returns the vector containing the coordnates of the texture
  53851. */
  53852. PickingInfo.prototype.getTextureCoordinates = function () {
  53853. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53854. return null;
  53855. }
  53856. var indices = this.pickedMesh.getIndices();
  53857. if (!indices) {
  53858. return null;
  53859. }
  53860. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53861. if (!uvs) {
  53862. return null;
  53863. }
  53864. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53865. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53866. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53867. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53868. uv1 = uv1.scale(this.bu);
  53869. uv2 = uv2.scale(this.bv);
  53870. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53871. };
  53872. return PickingInfo;
  53873. }());
  53874. BABYLON.PickingInfo = PickingInfo;
  53875. })(BABYLON || (BABYLON = {}));
  53876. //# sourceMappingURL=babylon.pickingInfo.js.map
  53877. var BABYLON;
  53878. (function (BABYLON) {
  53879. var Ray = /** @class */ (function () {
  53880. function Ray(origin, direction, length) {
  53881. if (length === void 0) { length = Number.MAX_VALUE; }
  53882. this.origin = origin;
  53883. this.direction = direction;
  53884. this.length = length;
  53885. }
  53886. // Methods
  53887. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53888. var d = 0.0;
  53889. var maxValue = Number.MAX_VALUE;
  53890. var inv;
  53891. var min;
  53892. var max;
  53893. var temp;
  53894. if (Math.abs(this.direction.x) < 0.0000001) {
  53895. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53896. return false;
  53897. }
  53898. }
  53899. else {
  53900. inv = 1.0 / this.direction.x;
  53901. min = (minimum.x - this.origin.x) * inv;
  53902. max = (maximum.x - this.origin.x) * inv;
  53903. if (max === -Infinity) {
  53904. max = Infinity;
  53905. }
  53906. if (min > max) {
  53907. temp = min;
  53908. min = max;
  53909. max = temp;
  53910. }
  53911. d = Math.max(min, d);
  53912. maxValue = Math.min(max, maxValue);
  53913. if (d > maxValue) {
  53914. return false;
  53915. }
  53916. }
  53917. if (Math.abs(this.direction.y) < 0.0000001) {
  53918. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53919. return false;
  53920. }
  53921. }
  53922. else {
  53923. inv = 1.0 / this.direction.y;
  53924. min = (minimum.y - this.origin.y) * inv;
  53925. max = (maximum.y - this.origin.y) * inv;
  53926. if (max === -Infinity) {
  53927. max = Infinity;
  53928. }
  53929. if (min > max) {
  53930. temp = min;
  53931. min = max;
  53932. max = temp;
  53933. }
  53934. d = Math.max(min, d);
  53935. maxValue = Math.min(max, maxValue);
  53936. if (d > maxValue) {
  53937. return false;
  53938. }
  53939. }
  53940. if (Math.abs(this.direction.z) < 0.0000001) {
  53941. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53942. return false;
  53943. }
  53944. }
  53945. else {
  53946. inv = 1.0 / this.direction.z;
  53947. min = (minimum.z - this.origin.z) * inv;
  53948. max = (maximum.z - this.origin.z) * inv;
  53949. if (max === -Infinity) {
  53950. max = Infinity;
  53951. }
  53952. if (min > max) {
  53953. temp = min;
  53954. min = max;
  53955. max = temp;
  53956. }
  53957. d = Math.max(min, d);
  53958. maxValue = Math.min(max, maxValue);
  53959. if (d > maxValue) {
  53960. return false;
  53961. }
  53962. }
  53963. return true;
  53964. };
  53965. Ray.prototype.intersectsBox = function (box) {
  53966. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53967. };
  53968. Ray.prototype.intersectsSphere = function (sphere) {
  53969. var x = sphere.center.x - this.origin.x;
  53970. var y = sphere.center.y - this.origin.y;
  53971. var z = sphere.center.z - this.origin.z;
  53972. var pyth = (x * x) + (y * y) + (z * z);
  53973. var rr = sphere.radius * sphere.radius;
  53974. if (pyth <= rr) {
  53975. return true;
  53976. }
  53977. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53978. if (dot < 0.0) {
  53979. return false;
  53980. }
  53981. var temp = pyth - (dot * dot);
  53982. return temp <= rr;
  53983. };
  53984. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53985. if (!this._edge1) {
  53986. this._edge1 = BABYLON.Vector3.Zero();
  53987. this._edge2 = BABYLON.Vector3.Zero();
  53988. this._pvec = BABYLON.Vector3.Zero();
  53989. this._tvec = BABYLON.Vector3.Zero();
  53990. this._qvec = BABYLON.Vector3.Zero();
  53991. }
  53992. vertex1.subtractToRef(vertex0, this._edge1);
  53993. vertex2.subtractToRef(vertex0, this._edge2);
  53994. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53995. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53996. if (det === 0) {
  53997. return null;
  53998. }
  53999. var invdet = 1 / det;
  54000. this.origin.subtractToRef(vertex0, this._tvec);
  54001. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54002. if (bu < 0 || bu > 1.0) {
  54003. return null;
  54004. }
  54005. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54006. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54007. if (bv < 0 || bu + bv > 1.0) {
  54008. return null;
  54009. }
  54010. //check if the distance is longer than the predefined length.
  54011. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54012. if (distance > this.length) {
  54013. return null;
  54014. }
  54015. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54016. };
  54017. Ray.prototype.intersectsPlane = function (plane) {
  54018. var distance;
  54019. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54020. if (Math.abs(result1) < 9.99999997475243E-07) {
  54021. return null;
  54022. }
  54023. else {
  54024. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54025. distance = (-plane.d - result2) / result1;
  54026. if (distance < 0.0) {
  54027. if (distance < -9.99999997475243E-07) {
  54028. return null;
  54029. }
  54030. else {
  54031. return 0;
  54032. }
  54033. }
  54034. return distance;
  54035. }
  54036. };
  54037. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54038. var tm = BABYLON.Tmp.Matrix[0];
  54039. mesh.getWorldMatrix().invertToRef(tm);
  54040. if (this._tmpRay) {
  54041. Ray.TransformToRef(this, tm, this._tmpRay);
  54042. }
  54043. else {
  54044. this._tmpRay = Ray.Transform(this, tm);
  54045. }
  54046. return mesh.intersects(this._tmpRay, fastCheck);
  54047. };
  54048. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54049. if (results) {
  54050. results.length = 0;
  54051. }
  54052. else {
  54053. results = [];
  54054. }
  54055. for (var i = 0; i < meshes.length; i++) {
  54056. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54057. if (pickInfo.hit) {
  54058. results.push(pickInfo);
  54059. }
  54060. }
  54061. results.sort(this._comparePickingInfo);
  54062. return results;
  54063. };
  54064. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54065. if (pickingInfoA.distance < pickingInfoB.distance) {
  54066. return -1;
  54067. }
  54068. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54069. return 1;
  54070. }
  54071. else {
  54072. return 0;
  54073. }
  54074. };
  54075. /**
  54076. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54077. * @param sega the first point of the segment to test the intersection against
  54078. * @param segb the second point of the segment to test the intersection against
  54079. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54080. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54081. */
  54082. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54083. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54084. var u = segb.subtract(sega);
  54085. var v = rsegb.subtract(this.origin);
  54086. var w = sega.subtract(this.origin);
  54087. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54088. var b = BABYLON.Vector3.Dot(u, v);
  54089. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54090. var d = BABYLON.Vector3.Dot(u, w);
  54091. var e = BABYLON.Vector3.Dot(v, w);
  54092. var D = a * c - b * b; // always >= 0
  54093. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54094. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54095. // compute the line parameters of the two closest points
  54096. if (D < Ray.smallnum) { // the lines are almost parallel
  54097. sN = 0.0; // force using point P0 on segment S1
  54098. sD = 1.0; // to prevent possible division by 0.0 later
  54099. tN = e;
  54100. tD = c;
  54101. }
  54102. else { // get the closest points on the infinite lines
  54103. sN = (b * e - c * d);
  54104. tN = (a * e - b * d);
  54105. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54106. sN = 0.0;
  54107. tN = e;
  54108. tD = c;
  54109. }
  54110. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54111. sN = sD;
  54112. tN = e + b;
  54113. tD = c;
  54114. }
  54115. }
  54116. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54117. tN = 0.0;
  54118. // recompute sc for this edge
  54119. if (-d < 0.0) {
  54120. sN = 0.0;
  54121. }
  54122. else if (-d > a)
  54123. sN = sD;
  54124. else {
  54125. sN = -d;
  54126. sD = a;
  54127. }
  54128. }
  54129. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54130. tN = tD;
  54131. // recompute sc for this edge
  54132. if ((-d + b) < 0.0) {
  54133. sN = 0;
  54134. }
  54135. else if ((-d + b) > a) {
  54136. sN = sD;
  54137. }
  54138. else {
  54139. sN = (-d + b);
  54140. sD = a;
  54141. }
  54142. }
  54143. // finally do the division to get sc and tc
  54144. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54145. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54146. // get the difference of the two closest points
  54147. var qtc = v.multiplyByFloats(tc, tc, tc);
  54148. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54149. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54150. if (isIntersected) {
  54151. return qtc.length();
  54152. }
  54153. return -1;
  54154. };
  54155. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54156. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54157. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54158. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54159. this.direction.normalize();
  54160. return this;
  54161. };
  54162. // Statics
  54163. Ray.Zero = function () {
  54164. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54165. };
  54166. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54167. var result = Ray.Zero();
  54168. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54169. };
  54170. /**
  54171. * 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
  54172. * transformed to the given world matrix.
  54173. * @param origin The origin point
  54174. * @param end The end point
  54175. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54176. */
  54177. Ray.CreateNewFromTo = function (origin, end, world) {
  54178. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54179. var direction = end.subtract(origin);
  54180. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54181. direction.normalize();
  54182. return Ray.Transform(new Ray(origin, direction, length), world);
  54183. };
  54184. Ray.Transform = function (ray, matrix) {
  54185. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54186. Ray.TransformToRef(ray, matrix, result);
  54187. return result;
  54188. };
  54189. Ray.TransformToRef = function (ray, matrix, result) {
  54190. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54191. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54192. result.length = ray.length;
  54193. var dir = result.direction;
  54194. var len = dir.length();
  54195. if (!(len === 0 || len === 1)) {
  54196. var num = 1.0 / len;
  54197. dir.x *= num;
  54198. dir.y *= num;
  54199. dir.z *= num;
  54200. result.length *= len;
  54201. }
  54202. };
  54203. Ray.smallnum = 0.00000001;
  54204. Ray.rayl = 10e8;
  54205. return Ray;
  54206. }());
  54207. BABYLON.Ray = Ray;
  54208. })(BABYLON || (BABYLON = {}));
  54209. //# sourceMappingURL=babylon.ray.js.map
  54210. var BABYLON;
  54211. (function (BABYLON) {
  54212. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54213. if (boxMin.x > sphereCenter.x + sphereRadius)
  54214. return false;
  54215. if (sphereCenter.x - sphereRadius > boxMax.x)
  54216. return false;
  54217. if (boxMin.y > sphereCenter.y + sphereRadius)
  54218. return false;
  54219. if (sphereCenter.y - sphereRadius > boxMax.y)
  54220. return false;
  54221. if (boxMin.z > sphereCenter.z + sphereRadius)
  54222. return false;
  54223. if (sphereCenter.z - sphereRadius > boxMax.z)
  54224. return false;
  54225. return true;
  54226. };
  54227. var getLowestRoot = (function () {
  54228. var result = { root: 0, found: false };
  54229. return function (a, b, c, maxR) {
  54230. result.root = 0;
  54231. result.found = false;
  54232. var determinant = b * b - 4.0 * a * c;
  54233. if (determinant < 0)
  54234. return result;
  54235. var sqrtD = Math.sqrt(determinant);
  54236. var r1 = (-b - sqrtD) / (2.0 * a);
  54237. var r2 = (-b + sqrtD) / (2.0 * a);
  54238. if (r1 > r2) {
  54239. var temp = r2;
  54240. r2 = r1;
  54241. r1 = temp;
  54242. }
  54243. if (r1 > 0 && r1 < maxR) {
  54244. result.root = r1;
  54245. result.found = true;
  54246. return result;
  54247. }
  54248. if (r2 > 0 && r2 < maxR) {
  54249. result.root = r2;
  54250. result.found = true;
  54251. return result;
  54252. }
  54253. return result;
  54254. };
  54255. })();
  54256. var Collider = /** @class */ (function () {
  54257. function Collider() {
  54258. this._collisionPoint = BABYLON.Vector3.Zero();
  54259. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54260. this._tempVector = BABYLON.Vector3.Zero();
  54261. this._tempVector2 = BABYLON.Vector3.Zero();
  54262. this._tempVector3 = BABYLON.Vector3.Zero();
  54263. this._tempVector4 = BABYLON.Vector3.Zero();
  54264. this._edge = BABYLON.Vector3.Zero();
  54265. this._baseToVertex = BABYLON.Vector3.Zero();
  54266. this._destinationPoint = BABYLON.Vector3.Zero();
  54267. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54268. this._displacementVector = BABYLON.Vector3.Zero();
  54269. this._radius = BABYLON.Vector3.One();
  54270. this._retry = 0;
  54271. this._basePointWorld = BABYLON.Vector3.Zero();
  54272. this._velocityWorld = BABYLON.Vector3.Zero();
  54273. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54274. this._collisionMask = -1;
  54275. }
  54276. Object.defineProperty(Collider.prototype, "collisionMask", {
  54277. get: function () {
  54278. return this._collisionMask;
  54279. },
  54280. set: function (mask) {
  54281. this._collisionMask = !isNaN(mask) ? mask : -1;
  54282. },
  54283. enumerable: true,
  54284. configurable: true
  54285. });
  54286. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54287. /**
  54288. * Gets the plane normal used to compute the sliding response (in local space)
  54289. */
  54290. get: function () {
  54291. return this._slidePlaneNormal;
  54292. },
  54293. enumerable: true,
  54294. configurable: true
  54295. });
  54296. // Methods
  54297. Collider.prototype._initialize = function (source, dir, e) {
  54298. this._velocity = dir;
  54299. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54300. this._basePoint = source;
  54301. source.multiplyToRef(this._radius, this._basePointWorld);
  54302. dir.multiplyToRef(this._radius, this._velocityWorld);
  54303. this._velocityWorldLength = this._velocityWorld.length();
  54304. this._epsilon = e;
  54305. this.collisionFound = false;
  54306. };
  54307. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54308. pa.subtractToRef(point, this._tempVector);
  54309. pb.subtractToRef(point, this._tempVector2);
  54310. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54311. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54312. if (d < 0)
  54313. return false;
  54314. pc.subtractToRef(point, this._tempVector3);
  54315. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54316. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54317. if (d < 0)
  54318. return false;
  54319. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54320. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54321. return d >= 0;
  54322. };
  54323. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54324. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54325. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54326. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54327. return false;
  54328. }
  54329. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54330. return false;
  54331. return true;
  54332. };
  54333. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54334. var t0;
  54335. var embeddedInPlane = false;
  54336. //defensive programming, actually not needed.
  54337. if (!trianglePlaneArray) {
  54338. trianglePlaneArray = [];
  54339. }
  54340. if (!trianglePlaneArray[faceIndex]) {
  54341. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54342. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54343. }
  54344. var trianglePlane = trianglePlaneArray[faceIndex];
  54345. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54346. return;
  54347. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54348. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54349. if (normalDotVelocity == 0) {
  54350. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54351. return;
  54352. embeddedInPlane = true;
  54353. t0 = 0;
  54354. }
  54355. else {
  54356. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54357. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54358. if (t0 > t1) {
  54359. var temp = t1;
  54360. t1 = t0;
  54361. t0 = temp;
  54362. }
  54363. if (t0 > 1.0 || t1 < 0.0)
  54364. return;
  54365. if (t0 < 0)
  54366. t0 = 0;
  54367. if (t0 > 1.0)
  54368. t0 = 1.0;
  54369. }
  54370. this._collisionPoint.copyFromFloats(0, 0, 0);
  54371. var found = false;
  54372. var t = 1.0;
  54373. if (!embeddedInPlane) {
  54374. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54375. this._velocity.scaleToRef(t0, this._tempVector);
  54376. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54377. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54378. found = true;
  54379. t = t0;
  54380. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54381. }
  54382. }
  54383. if (!found) {
  54384. var velocitySquaredLength = this._velocity.lengthSquared();
  54385. var a = velocitySquaredLength;
  54386. this._basePoint.subtractToRef(p1, this._tempVector);
  54387. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54388. var c = this._tempVector.lengthSquared() - 1.0;
  54389. var lowestRoot = getLowestRoot(a, b, c, t);
  54390. if (lowestRoot.found) {
  54391. t = lowestRoot.root;
  54392. found = true;
  54393. this._collisionPoint.copyFrom(p1);
  54394. }
  54395. this._basePoint.subtractToRef(p2, this._tempVector);
  54396. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54397. c = this._tempVector.lengthSquared() - 1.0;
  54398. lowestRoot = getLowestRoot(a, b, c, t);
  54399. if (lowestRoot.found) {
  54400. t = lowestRoot.root;
  54401. found = true;
  54402. this._collisionPoint.copyFrom(p2);
  54403. }
  54404. this._basePoint.subtractToRef(p3, this._tempVector);
  54405. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54406. c = this._tempVector.lengthSquared() - 1.0;
  54407. lowestRoot = getLowestRoot(a, b, c, t);
  54408. if (lowestRoot.found) {
  54409. t = lowestRoot.root;
  54410. found = true;
  54411. this._collisionPoint.copyFrom(p3);
  54412. }
  54413. p2.subtractToRef(p1, this._edge);
  54414. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54415. var edgeSquaredLength = this._edge.lengthSquared();
  54416. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54417. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54418. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54419. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54420. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54421. lowestRoot = getLowestRoot(a, b, c, t);
  54422. if (lowestRoot.found) {
  54423. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54424. if (f >= 0.0 && f <= 1.0) {
  54425. t = lowestRoot.root;
  54426. found = true;
  54427. this._edge.scaleInPlace(f);
  54428. p1.addToRef(this._edge, this._collisionPoint);
  54429. }
  54430. }
  54431. p3.subtractToRef(p2, this._edge);
  54432. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54433. edgeSquaredLength = this._edge.lengthSquared();
  54434. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54435. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54436. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54437. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54438. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54439. lowestRoot = getLowestRoot(a, b, c, t);
  54440. if (lowestRoot.found) {
  54441. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54442. if (f >= 0.0 && f <= 1.0) {
  54443. t = lowestRoot.root;
  54444. found = true;
  54445. this._edge.scaleInPlace(f);
  54446. p2.addToRef(this._edge, this._collisionPoint);
  54447. }
  54448. }
  54449. p1.subtractToRef(p3, this._edge);
  54450. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54451. edgeSquaredLength = this._edge.lengthSquared();
  54452. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54453. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54454. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54455. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54456. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54457. lowestRoot = getLowestRoot(a, b, c, t);
  54458. if (lowestRoot.found) {
  54459. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54460. if (f >= 0.0 && f <= 1.0) {
  54461. t = lowestRoot.root;
  54462. found = true;
  54463. this._edge.scaleInPlace(f);
  54464. p3.addToRef(this._edge, this._collisionPoint);
  54465. }
  54466. }
  54467. }
  54468. if (found) {
  54469. var distToCollision = t * this._velocity.length();
  54470. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54471. if (!this.intersectionPoint) {
  54472. this.intersectionPoint = this._collisionPoint.clone();
  54473. }
  54474. else {
  54475. this.intersectionPoint.copyFrom(this._collisionPoint);
  54476. }
  54477. this._nearestDistance = distToCollision;
  54478. this.collisionFound = true;
  54479. }
  54480. }
  54481. };
  54482. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54483. for (var i = indexStart; i < indexEnd; i += 3) {
  54484. var p1 = pts[indices[i] - decal];
  54485. var p2 = pts[indices[i + 1] - decal];
  54486. var p3 = pts[indices[i + 2] - decal];
  54487. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54488. }
  54489. };
  54490. Collider.prototype._getResponse = function (pos, vel) {
  54491. pos.addToRef(vel, this._destinationPoint);
  54492. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54493. this._basePoint.addToRef(vel, pos);
  54494. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54495. this._slidePlaneNormal.normalize();
  54496. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54497. pos.addInPlace(this._displacementVector);
  54498. this.intersectionPoint.addInPlace(this._displacementVector);
  54499. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54500. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54501. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54502. };
  54503. return Collider;
  54504. }());
  54505. BABYLON.Collider = Collider;
  54506. })(BABYLON || (BABYLON = {}));
  54507. //# sourceMappingURL=babylon.collider.js.map
  54508. var BABYLON;
  54509. (function (BABYLON) {
  54510. //WebWorker code will be inserted to this variable.
  54511. BABYLON.CollisionWorker = "";
  54512. /** Defines supported task for worker process */
  54513. var WorkerTaskType;
  54514. (function (WorkerTaskType) {
  54515. /** Initialization */
  54516. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54517. /** Update of geometry */
  54518. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54519. /** Evaluate collision */
  54520. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54521. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54522. /** Defines kind of replies returned by worker */
  54523. var WorkerReplyType;
  54524. (function (WorkerReplyType) {
  54525. /** Success */
  54526. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54527. /** Unkown error */
  54528. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54529. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54530. var CollisionCoordinatorWorker = /** @class */ (function () {
  54531. function CollisionCoordinatorWorker() {
  54532. var _this = this;
  54533. this._scaledPosition = BABYLON.Vector3.Zero();
  54534. this._scaledVelocity = BABYLON.Vector3.Zero();
  54535. this.onMeshUpdated = function (transformNode) {
  54536. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54537. };
  54538. this.onGeometryUpdated = function (geometry) {
  54539. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54540. };
  54541. this._afterRender = function () {
  54542. if (!_this._init)
  54543. return;
  54544. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54545. return;
  54546. }
  54547. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54548. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54549. if (_this._runningUpdated > 4) {
  54550. return;
  54551. }
  54552. ++_this._runningUpdated;
  54553. var payload = {
  54554. updatedMeshes: _this._addUpdateMeshesList,
  54555. updatedGeometries: _this._addUpdateGeometriesList,
  54556. removedGeometries: _this._toRemoveGeometryArray,
  54557. removedMeshes: _this._toRemoveMeshesArray
  54558. };
  54559. var message = {
  54560. payload: payload,
  54561. taskType: WorkerTaskType.UPDATE
  54562. };
  54563. var serializable = [];
  54564. for (var id in payload.updatedGeometries) {
  54565. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54566. //prepare transferables
  54567. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54568. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54569. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54570. }
  54571. }
  54572. _this._worker.postMessage(message, serializable);
  54573. _this._addUpdateMeshesList = {};
  54574. _this._addUpdateGeometriesList = {};
  54575. _this._toRemoveGeometryArray = [];
  54576. _this._toRemoveMeshesArray = [];
  54577. };
  54578. this._onMessageFromWorker = function (e) {
  54579. var returnData = e.data;
  54580. if (returnData.error != WorkerReplyType.SUCCESS) {
  54581. //TODO what errors can be returned from the worker?
  54582. BABYLON.Tools.Warn("error returned from worker!");
  54583. return;
  54584. }
  54585. switch (returnData.taskType) {
  54586. case WorkerTaskType.INIT:
  54587. _this._init = true;
  54588. //Update the worked with ALL of the scene's current state
  54589. _this._scene.meshes.forEach(function (mesh) {
  54590. _this.onMeshAdded(mesh);
  54591. });
  54592. _this._scene.getGeometries().forEach(function (geometry) {
  54593. _this.onGeometryAdded(geometry);
  54594. });
  54595. break;
  54596. case WorkerTaskType.UPDATE:
  54597. _this._runningUpdated--;
  54598. break;
  54599. case WorkerTaskType.COLLIDE:
  54600. var returnPayload = returnData.payload;
  54601. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54602. return;
  54603. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54604. if (callback) {
  54605. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54606. if (mesh) {
  54607. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54608. }
  54609. }
  54610. //cleanup
  54611. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54612. break;
  54613. }
  54614. };
  54615. this._collisionsCallbackArray = [];
  54616. this._init = false;
  54617. this._runningUpdated = 0;
  54618. this._addUpdateMeshesList = {};
  54619. this._addUpdateGeometriesList = {};
  54620. this._toRemoveGeometryArray = [];
  54621. this._toRemoveMeshesArray = [];
  54622. }
  54623. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54624. if (!this._init)
  54625. return;
  54626. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54627. return;
  54628. position.divideToRef(collider._radius, this._scaledPosition);
  54629. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54630. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54631. var payload = {
  54632. collider: {
  54633. position: this._scaledPosition.asArray(),
  54634. velocity: this._scaledVelocity.asArray(),
  54635. radius: collider._radius.asArray()
  54636. },
  54637. collisionId: collisionIndex,
  54638. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54639. maximumRetry: maximumRetry
  54640. };
  54641. var message = {
  54642. payload: payload,
  54643. taskType: WorkerTaskType.COLLIDE
  54644. };
  54645. this._worker.postMessage(message);
  54646. };
  54647. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54648. this._scene = scene;
  54649. this._scene.registerAfterRender(this._afterRender);
  54650. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54651. this._worker = new Worker(workerUrl);
  54652. this._worker.onmessage = this._onMessageFromWorker;
  54653. var message = {
  54654. payload: {},
  54655. taskType: WorkerTaskType.INIT
  54656. };
  54657. this._worker.postMessage(message);
  54658. };
  54659. CollisionCoordinatorWorker.prototype.destroy = function () {
  54660. this._scene.unregisterAfterRender(this._afterRender);
  54661. this._worker.terminate();
  54662. };
  54663. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54664. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54665. this.onMeshUpdated(mesh);
  54666. };
  54667. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54668. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54669. };
  54670. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54671. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54672. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54673. this.onGeometryUpdated(geometry);
  54674. };
  54675. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54676. this._toRemoveGeometryArray.push(geometry.id);
  54677. };
  54678. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54679. var submeshes = [];
  54680. if (mesh.subMeshes) {
  54681. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54682. var boundingInfo = sm.getBoundingInfo();
  54683. return {
  54684. position: idx,
  54685. verticesStart: sm.verticesStart,
  54686. verticesCount: sm.verticesCount,
  54687. indexStart: sm.indexStart,
  54688. indexCount: sm.indexCount,
  54689. hasMaterial: !!sm.getMaterial(),
  54690. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54691. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54692. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54693. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54694. };
  54695. });
  54696. }
  54697. var geometryId = null;
  54698. if (mesh instanceof BABYLON.Mesh) {
  54699. var geometry = mesh.geometry;
  54700. geometryId = geometry ? geometry.id : null;
  54701. }
  54702. else if (mesh instanceof BABYLON.InstancedMesh) {
  54703. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54704. geometryId = geometry ? geometry.id : null;
  54705. }
  54706. var boundingInfo = mesh.getBoundingInfo();
  54707. return {
  54708. uniqueId: mesh.uniqueId,
  54709. id: mesh.id,
  54710. name: mesh.name,
  54711. geometryId: geometryId,
  54712. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54713. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54714. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54715. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54716. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54717. subMeshes: submeshes,
  54718. checkCollisions: mesh.checkCollisions
  54719. };
  54720. };
  54721. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54722. return {
  54723. id: geometry.id,
  54724. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54725. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54726. indices: new Uint32Array(geometry.getIndices() || []),
  54727. };
  54728. };
  54729. return CollisionCoordinatorWorker;
  54730. }());
  54731. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54732. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54733. function CollisionCoordinatorLegacy() {
  54734. this._scaledPosition = BABYLON.Vector3.Zero();
  54735. this._scaledVelocity = BABYLON.Vector3.Zero();
  54736. this._finalPosition = BABYLON.Vector3.Zero();
  54737. }
  54738. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54739. position.divideToRef(collider._radius, this._scaledPosition);
  54740. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54741. collider.collidedMesh = null;
  54742. collider._retry = 0;
  54743. collider._initialVelocity = this._scaledVelocity;
  54744. collider._initialPosition = this._scaledPosition;
  54745. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54746. this._finalPosition.multiplyInPlace(collider._radius);
  54747. //run the callback
  54748. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54749. };
  54750. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54751. this._scene = scene;
  54752. };
  54753. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54754. //Legacy need no destruction method.
  54755. };
  54756. //No update in legacy mode
  54757. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54758. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54759. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54760. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54761. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54762. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54763. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54764. if (excludedMesh === void 0) { excludedMesh = null; }
  54765. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54766. if (collider._retry >= maximumRetry) {
  54767. finalPosition.copyFrom(position);
  54768. return;
  54769. }
  54770. // Check if this is a mesh else camera or -1
  54771. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54772. collider._initialize(position, velocity, closeDistance);
  54773. // Check all meshes
  54774. for (var index = 0; index < this._scene.meshes.length; index++) {
  54775. var mesh = this._scene.meshes[index];
  54776. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54777. mesh._checkCollision(collider);
  54778. }
  54779. }
  54780. if (!collider.collisionFound) {
  54781. position.addToRef(velocity, finalPosition);
  54782. return;
  54783. }
  54784. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54785. collider._getResponse(position, velocity);
  54786. }
  54787. if (velocity.length() <= closeDistance) {
  54788. finalPosition.copyFrom(position);
  54789. return;
  54790. }
  54791. collider._retry++;
  54792. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54793. };
  54794. return CollisionCoordinatorLegacy;
  54795. }());
  54796. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54797. })(BABYLON || (BABYLON = {}));
  54798. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54799. var BABYLON;
  54800. (function (BABYLON) {
  54801. /**
  54802. * A particle represents one of the element emitted by a particle system.
  54803. * This is mainly define by its coordinates, direction, velocity and age.
  54804. */
  54805. var Particle = /** @class */ (function () {
  54806. /**
  54807. * Creates a new instance Particle
  54808. * @param particleSystem the particle system the particle belongs to
  54809. */
  54810. function Particle(
  54811. /**
  54812. * particleSystem the particle system the particle belongs to.
  54813. */
  54814. particleSystem) {
  54815. this.particleSystem = particleSystem;
  54816. /**
  54817. * The world position of the particle in the scene.
  54818. */
  54819. this.position = BABYLON.Vector3.Zero();
  54820. /**
  54821. * The world direction of the particle in the scene.
  54822. */
  54823. this.direction = BABYLON.Vector3.Zero();
  54824. /**
  54825. * The color of the particle.
  54826. */
  54827. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54828. /**
  54829. * The color change of the particle per step.
  54830. */
  54831. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54832. /**
  54833. * Defines how long will the life of the particle be.
  54834. */
  54835. this.lifeTime = 1.0;
  54836. /**
  54837. * The current age of the particle.
  54838. */
  54839. this.age = 0;
  54840. /**
  54841. * The current size of the particle.
  54842. */
  54843. this.size = 0;
  54844. /**
  54845. * The current scale of the particle.
  54846. */
  54847. this.scale = new BABYLON.Vector2(1, 1);
  54848. /**
  54849. * The current angle of the particle.
  54850. */
  54851. this.angle = 0;
  54852. /**
  54853. * Defines how fast is the angle changing.
  54854. */
  54855. this.angularSpeed = 0;
  54856. /**
  54857. * Defines the cell index used by the particle to be rendered from a sprite.
  54858. */
  54859. this.cellIndex = 0;
  54860. this._currentFrameCounter = 0;
  54861. /** @hidden */
  54862. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54863. /** @hidden */
  54864. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54865. if (!this.particleSystem.isAnimationSheetEnabled) {
  54866. return;
  54867. }
  54868. this.updateCellInfoFromSystem();
  54869. }
  54870. Particle.prototype.updateCellInfoFromSystem = function () {
  54871. this.cellIndex = this.particleSystem.startSpriteCellID;
  54872. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54873. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54874. }
  54875. else {
  54876. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54877. }
  54878. };
  54879. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54880. // (ageOffset / scaledUpdateSpeed) / available cells
  54881. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54882. this._currentFrameCounter += scaledUpdateSpeed;
  54883. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54884. this._currentFrameCounter = 0;
  54885. this.cellIndex++;
  54886. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54887. this.cellIndex = this.particleSystem.endSpriteCellID;
  54888. }
  54889. }
  54890. };
  54891. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54892. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54893. this.cellIndex++;
  54894. this._currentFrameCounter = 0;
  54895. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54896. if (this.particleSystem.spriteCellLoop) {
  54897. this.cellIndex = this.particleSystem.startSpriteCellID;
  54898. }
  54899. else {
  54900. this.cellIndex = this.particleSystem.endSpriteCellID;
  54901. }
  54902. }
  54903. }
  54904. else {
  54905. this._currentFrameCounter++;
  54906. }
  54907. };
  54908. /**
  54909. * Copy the properties of particle to another one.
  54910. * @param other the particle to copy the information to.
  54911. */
  54912. Particle.prototype.copyTo = function (other) {
  54913. other.position.copyFrom(this.position);
  54914. if (this._initialDirection) {
  54915. if (other._initialDirection) {
  54916. other._initialDirection.copyFrom(this._initialDirection);
  54917. }
  54918. else {
  54919. other._initialDirection = this._initialDirection.clone();
  54920. }
  54921. }
  54922. else {
  54923. other._initialDirection = null;
  54924. }
  54925. other.direction.copyFrom(this.direction);
  54926. other.color.copyFrom(this.color);
  54927. other.colorStep.copyFrom(this.colorStep);
  54928. other.lifeTime = this.lifeTime;
  54929. other.age = this.age;
  54930. other.size = this.size;
  54931. other.scale.copyFrom(this.scale);
  54932. other.angle = this.angle;
  54933. other.angularSpeed = this.angularSpeed;
  54934. other.particleSystem = this.particleSystem;
  54935. other.cellIndex = this.cellIndex;
  54936. if (this._currentColorGradient) {
  54937. other._currentColorGradient = this._currentColorGradient;
  54938. other._currentColor1.copyFrom(this._currentColor1);
  54939. other._currentColor2.copyFrom(this._currentColor2);
  54940. }
  54941. };
  54942. return Particle;
  54943. }());
  54944. BABYLON.Particle = Particle;
  54945. })(BABYLON || (BABYLON = {}));
  54946. //# sourceMappingURL=babylon.particle.js.map
  54947. var BABYLON;
  54948. (function (BABYLON) {
  54949. /**
  54950. * This represents a particle system in Babylon.
  54951. * 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.
  54952. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54953. * @example https://doc.babylonjs.com/babylon101/particles
  54954. */
  54955. var ParticleSystem = /** @class */ (function () {
  54956. /**
  54957. * Instantiates a particle system.
  54958. * 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.
  54959. * @param name The name of the particle system
  54960. * @param capacity The max number of particles alive at the same time
  54961. * @param scene The scene the particle system belongs to
  54962. * @param customEffect a custom effect used to change the way particles are rendered by default
  54963. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54964. * @param epsilon Offset used to render the particles
  54965. */
  54966. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54967. if (customEffect === void 0) { customEffect = null; }
  54968. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54969. if (epsilon === void 0) { epsilon = 0.01; }
  54970. var _this = this;
  54971. /**
  54972. * List of animations used by the particle system.
  54973. */
  54974. this.animations = [];
  54975. /**
  54976. * The rendering group used by the Particle system to chose when to render.
  54977. */
  54978. this.renderingGroupId = 0;
  54979. /**
  54980. * The emitter represents the Mesh or position we are attaching the particle system to.
  54981. */
  54982. this.emitter = null;
  54983. /**
  54984. * The maximum number of particles to emit per frame
  54985. */
  54986. this.emitRate = 10;
  54987. /**
  54988. * If you want to launch only a few particles at once, that can be done, as well.
  54989. */
  54990. this.manualEmitCount = -1;
  54991. /**
  54992. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54993. */
  54994. this.updateSpeed = 0.01;
  54995. /**
  54996. * The amount of time the particle system is running (depends of the overall update speed).
  54997. */
  54998. this.targetStopDuration = 0;
  54999. /**
  55000. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55001. */
  55002. this.disposeOnStop = false;
  55003. /**
  55004. * Minimum power of emitting particles.
  55005. */
  55006. this.minEmitPower = 1;
  55007. /**
  55008. * Maximum power of emitting particles.
  55009. */
  55010. this.maxEmitPower = 1;
  55011. /**
  55012. * Minimum life time of emitting particles.
  55013. */
  55014. this.minLifeTime = 1;
  55015. /**
  55016. * Maximum life time of emitting particles.
  55017. */
  55018. this.maxLifeTime = 1;
  55019. /**
  55020. * Minimum Size of emitting particles.
  55021. */
  55022. this.minSize = 1;
  55023. /**
  55024. * Maximum Size of emitting particles.
  55025. */
  55026. this.maxSize = 1;
  55027. /**
  55028. * Minimum scale of emitting particles on X axis.
  55029. */
  55030. this.minScaleX = 1;
  55031. /**
  55032. * Maximum scale of emitting particles on X axis.
  55033. */
  55034. this.maxScaleX = 1;
  55035. /**
  55036. * Minimum scale of emitting particles on Y axis.
  55037. */
  55038. this.minScaleY = 1;
  55039. /**
  55040. * Maximum scale of emitting particles on Y axis.
  55041. */
  55042. this.maxScaleY = 1;
  55043. /**
  55044. * Gets or sets the minimal initial rotation in radians.
  55045. */
  55046. this.minInitialRotation = 0;
  55047. /**
  55048. * Gets or sets the maximal initial rotation in radians.
  55049. */
  55050. this.maxInitialRotation = 0;
  55051. /**
  55052. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55053. */
  55054. this.minAngularSpeed = 0;
  55055. /**
  55056. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55057. */
  55058. this.maxAngularSpeed = 0;
  55059. /**
  55060. * The layer mask we are rendering the particles through.
  55061. */
  55062. this.layerMask = 0x0FFFFFFF;
  55063. /**
  55064. * This can help using your own shader to render the particle system.
  55065. * The according effect will be created
  55066. */
  55067. this.customShader = null;
  55068. /**
  55069. * By default particle system starts as soon as they are created. This prevents the
  55070. * automatic start to happen and let you decide when to start emitting particles.
  55071. */
  55072. this.preventAutoStart = false;
  55073. /**
  55074. * Callback triggered when the particle animation is ending.
  55075. */
  55076. this.onAnimationEnd = null;
  55077. /**
  55078. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55079. */
  55080. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55081. /**
  55082. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55083. * to override the particles.
  55084. */
  55085. this.forceDepthWrite = false;
  55086. /**
  55087. * You can use gravity if you want to give an orientation to your particles.
  55088. */
  55089. this.gravity = BABYLON.Vector3.Zero();
  55090. this._colorGradients = null;
  55091. this._sizeGradients = null;
  55092. /**
  55093. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55094. */
  55095. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55096. /**
  55097. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55098. */
  55099. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55100. /**
  55101. * Color the particle will have at the end of its lifetime
  55102. */
  55103. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55104. /**
  55105. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55106. */
  55107. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55108. /**
  55109. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not
  55110. */
  55111. this.spriteCellLoop = true;
  55112. /**
  55113. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop
  55114. */
  55115. this.spriteCellChangeSpeed = 0;
  55116. /**
  55117. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display
  55118. */
  55119. this.startSpriteCellID = 0;
  55120. /**
  55121. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display
  55122. */
  55123. this.endSpriteCellID = 0;
  55124. /**
  55125. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55126. */
  55127. this.spriteCellWidth = 0;
  55128. /**
  55129. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55130. */
  55131. this.spriteCellHeight = 0;
  55132. /** 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 */
  55133. this.preWarmCycles = 0;
  55134. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55135. this.preWarmStepOffset = 1;
  55136. /**
  55137. * An event triggered when the system is disposed
  55138. */
  55139. this.onDisposeObservable = new BABYLON.Observable();
  55140. this._particles = new Array();
  55141. this._stockParticles = new Array();
  55142. this._newPartsExcess = 0;
  55143. this._vertexBuffers = {};
  55144. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55145. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55146. this._scaledDirection = BABYLON.Vector3.Zero();
  55147. this._scaledGravity = BABYLON.Vector3.Zero();
  55148. this._currentRenderId = -1;
  55149. this._useInstancing = false;
  55150. this._started = false;
  55151. this._stopped = false;
  55152. this._actualFrame = 0;
  55153. this._isBillboardBased = true;
  55154. // start of sub system methods
  55155. /**
  55156. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55157. * Its lifetime will start back at 0.
  55158. */
  55159. this.recycleParticle = function (particle) {
  55160. var lastParticle = _this._particles.pop();
  55161. if (lastParticle !== particle) {
  55162. lastParticle.copyTo(particle);
  55163. }
  55164. _this._stockParticles.push(lastParticle);
  55165. };
  55166. this._createParticle = function () {
  55167. var particle;
  55168. if (_this._stockParticles.length !== 0) {
  55169. particle = _this._stockParticles.pop();
  55170. particle.age = 0;
  55171. particle._currentColorGradient = null;
  55172. particle.cellIndex = _this.startSpriteCellID;
  55173. }
  55174. else {
  55175. particle = new BABYLON.Particle(_this);
  55176. }
  55177. return particle;
  55178. };
  55179. this._emitFromParticle = function (particle) {
  55180. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55181. return;
  55182. }
  55183. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55184. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55185. subSystem._rootParticleSystem = _this;
  55186. _this.activeSubSystems.push(subSystem);
  55187. subSystem.start();
  55188. };
  55189. this.id = name;
  55190. this.name = name;
  55191. this._capacity = capacity;
  55192. this._epsilon = epsilon;
  55193. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55194. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55195. this._customEffect = customEffect;
  55196. scene.particleSystems.push(this);
  55197. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55198. this._createIndexBuffer();
  55199. this._createVertexBuffers();
  55200. // Default emitter type
  55201. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55202. this.updateFunction = function (particles) {
  55203. for (var index = 0; index < particles.length; index++) {
  55204. var particle = particles[index];
  55205. particle.age += _this._scaledUpdateSpeed;
  55206. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55207. _this._emitFromParticle(particle);
  55208. _this.recycleParticle(particle);
  55209. index--;
  55210. continue;
  55211. }
  55212. else {
  55213. var ratio = particle.age / particle.lifeTime;
  55214. // Color
  55215. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55216. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55217. if (currentGradient !== particle._currentColorGradient) {
  55218. particle._currentColor1.copyFrom(particle._currentColor2);
  55219. nextGradient.getColorToRef(particle._currentColor2);
  55220. particle._currentColorGradient = currentGradient;
  55221. }
  55222. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55223. });
  55224. }
  55225. else {
  55226. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55227. particle.color.addInPlace(_this._scaledColorStep);
  55228. if (particle.color.a < 0) {
  55229. particle.color.a = 0;
  55230. }
  55231. }
  55232. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55233. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55234. particle.position.addInPlace(_this._scaledDirection);
  55235. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55236. particle.direction.addInPlace(_this._scaledGravity);
  55237. // Gradient
  55238. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55239. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55240. particle.size = particle._initialSize * BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  55241. });
  55242. }
  55243. if (_this._isAnimationSheetEnabled) {
  55244. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55245. }
  55246. }
  55247. }
  55248. };
  55249. }
  55250. /**
  55251. * Gets the current list of color gradients.
  55252. * You must use addColorGradient and removeColorGradient to udpate this list
  55253. * @returns the list of color gradients
  55254. */
  55255. ParticleSystem.prototype.getColorGradients = function () {
  55256. return this._colorGradients;
  55257. };
  55258. /**
  55259. * Gets the current list of size gradients.
  55260. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55261. * @returns the list of size gradients
  55262. */
  55263. ParticleSystem.prototype.getSizeGradients = function () {
  55264. return this._sizeGradients;
  55265. };
  55266. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55267. /**
  55268. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55269. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55270. */
  55271. get: function () {
  55272. if (this.particleEmitterType.direction1) {
  55273. return this.particleEmitterType.direction1;
  55274. }
  55275. return BABYLON.Vector3.Zero();
  55276. },
  55277. set: function (value) {
  55278. if (this.particleEmitterType.direction1) {
  55279. this.particleEmitterType.direction1 = value;
  55280. }
  55281. },
  55282. enumerable: true,
  55283. configurable: true
  55284. });
  55285. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55286. /**
  55287. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55288. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55289. */
  55290. get: function () {
  55291. if (this.particleEmitterType.direction2) {
  55292. return this.particleEmitterType.direction2;
  55293. }
  55294. return BABYLON.Vector3.Zero();
  55295. },
  55296. set: function (value) {
  55297. if (this.particleEmitterType.direction2) {
  55298. this.particleEmitterType.direction2 = value;
  55299. }
  55300. },
  55301. enumerable: true,
  55302. configurable: true
  55303. });
  55304. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55305. /**
  55306. * 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.
  55307. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55308. */
  55309. get: function () {
  55310. if (this.particleEmitterType.minEmitBox) {
  55311. return this.particleEmitterType.minEmitBox;
  55312. }
  55313. return BABYLON.Vector3.Zero();
  55314. },
  55315. set: function (value) {
  55316. if (this.particleEmitterType.minEmitBox) {
  55317. this.particleEmitterType.minEmitBox = value;
  55318. }
  55319. },
  55320. enumerable: true,
  55321. configurable: true
  55322. });
  55323. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55324. /**
  55325. * 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.
  55326. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55327. */
  55328. get: function () {
  55329. if (this.particleEmitterType.maxEmitBox) {
  55330. return this.particleEmitterType.maxEmitBox;
  55331. }
  55332. return BABYLON.Vector3.Zero();
  55333. },
  55334. set: function (value) {
  55335. if (this.particleEmitterType.maxEmitBox) {
  55336. this.particleEmitterType.maxEmitBox = value;
  55337. }
  55338. },
  55339. enumerable: true,
  55340. configurable: true
  55341. });
  55342. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55343. /**
  55344. * Sets a callback that will be triggered when the system is disposed
  55345. */
  55346. set: function (callback) {
  55347. if (this._onDisposeObserver) {
  55348. this.onDisposeObservable.remove(this._onDisposeObserver);
  55349. }
  55350. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55351. },
  55352. enumerable: true,
  55353. configurable: true
  55354. });
  55355. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55356. /**
  55357. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55358. */
  55359. get: function () {
  55360. return this._isAnimationSheetEnabled;
  55361. },
  55362. enumerable: true,
  55363. configurable: true
  55364. });
  55365. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55366. /**
  55367. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55368. */
  55369. get: function () {
  55370. return this._isBillboardBased;
  55371. },
  55372. set: function (value) {
  55373. if (this._isBillboardBased === value) {
  55374. return;
  55375. }
  55376. this._isBillboardBased = value;
  55377. this._resetEffect();
  55378. },
  55379. enumerable: true,
  55380. configurable: true
  55381. });
  55382. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55383. //end of Sub-emitter
  55384. /**
  55385. * Gets the current list of active particles
  55386. */
  55387. get: function () {
  55388. return this._particles;
  55389. },
  55390. enumerable: true,
  55391. configurable: true
  55392. });
  55393. /**
  55394. * Returns the string "ParticleSystem"
  55395. * @returns a string containing the class name
  55396. */
  55397. ParticleSystem.prototype.getClassName = function () {
  55398. return "ParticleSystem";
  55399. };
  55400. /**
  55401. * Adds a new size gradient
  55402. * @param gradient defines the gradient to use (between 0 and 1)
  55403. * @param factor defines the size factor to affect to the specified gradient
  55404. */
  55405. ParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  55406. if (!this._sizeGradients) {
  55407. this._sizeGradients = [];
  55408. }
  55409. var sizeGradient = new BABYLON.FactorGradient();
  55410. sizeGradient.gradient = gradient;
  55411. sizeGradient.factor = factor;
  55412. this._sizeGradients.push(sizeGradient);
  55413. this._sizeGradients.sort(function (a, b) {
  55414. if (a.gradient < b.gradient) {
  55415. return -1;
  55416. }
  55417. else if (a.gradient > b.gradient) {
  55418. return 1;
  55419. }
  55420. return 0;
  55421. });
  55422. return this;
  55423. };
  55424. /**
  55425. * Remove a specific size gradient
  55426. * @param gradient defines the gradient to remove
  55427. */
  55428. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55429. if (!this._sizeGradients) {
  55430. return this;
  55431. }
  55432. var index = 0;
  55433. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  55434. var sizeGradient = _a[_i];
  55435. if (sizeGradient.gradient === gradient) {
  55436. this._sizeGradients.splice(index, 1);
  55437. break;
  55438. }
  55439. index++;
  55440. }
  55441. return this;
  55442. };
  55443. /**
  55444. * Adds a new color gradient
  55445. * @param gradient defines the gradient to use (between 0 and 1)
  55446. * @param color defines the color to affect to the specified gradient
  55447. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55448. */
  55449. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55450. if (!this._colorGradients) {
  55451. this._colorGradients = [];
  55452. }
  55453. var colorGradient = new BABYLON.ColorGradient();
  55454. colorGradient.gradient = gradient;
  55455. colorGradient.color1 = color;
  55456. colorGradient.color2 = color2;
  55457. this._colorGradients.push(colorGradient);
  55458. this._colorGradients.sort(function (a, b) {
  55459. if (a.gradient < b.gradient) {
  55460. return -1;
  55461. }
  55462. else if (a.gradient > b.gradient) {
  55463. return 1;
  55464. }
  55465. return 0;
  55466. });
  55467. return this;
  55468. };
  55469. /**
  55470. * Remove a specific color gradient
  55471. * @param gradient defines the gradient to remove
  55472. */
  55473. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55474. if (!this._colorGradients) {
  55475. return this;
  55476. }
  55477. var index = 0;
  55478. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55479. var colorGradient = _a[_i];
  55480. if (colorGradient.gradient === gradient) {
  55481. this._colorGradients.splice(index, 1);
  55482. break;
  55483. }
  55484. index++;
  55485. }
  55486. return this;
  55487. };
  55488. ParticleSystem.prototype._resetEffect = function () {
  55489. if (this._vertexBuffer) {
  55490. this._vertexBuffer.dispose();
  55491. this._vertexBuffer = null;
  55492. }
  55493. if (this._spriteBuffer) {
  55494. this._spriteBuffer.dispose();
  55495. this._spriteBuffer = null;
  55496. }
  55497. this._createVertexBuffers();
  55498. };
  55499. ParticleSystem.prototype._createVertexBuffers = function () {
  55500. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55501. if (this._isAnimationSheetEnabled) {
  55502. this._vertexBufferSize += 1;
  55503. }
  55504. if (!this._isBillboardBased) {
  55505. this._vertexBufferSize += 3;
  55506. }
  55507. var engine = this._scene.getEngine();
  55508. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55509. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55510. var dataOffset = 0;
  55511. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55512. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55513. dataOffset += 3;
  55514. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55515. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55516. dataOffset += 4;
  55517. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55518. this._vertexBuffers["angle"] = options;
  55519. dataOffset += 1;
  55520. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55521. this._vertexBuffers["size"] = size;
  55522. dataOffset += 2;
  55523. if (this._isAnimationSheetEnabled) {
  55524. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55525. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55526. dataOffset += 1;
  55527. }
  55528. if (!this._isBillboardBased) {
  55529. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55530. this._vertexBuffers["direction"] = directionBuffer;
  55531. dataOffset += 3;
  55532. }
  55533. var offsets;
  55534. if (this._useInstancing) {
  55535. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55536. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55537. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55538. }
  55539. else {
  55540. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55541. dataOffset += 2;
  55542. }
  55543. this._vertexBuffers["offset"] = offsets;
  55544. };
  55545. ParticleSystem.prototype._createIndexBuffer = function () {
  55546. if (this._useInstancing) {
  55547. return;
  55548. }
  55549. var indices = [];
  55550. var index = 0;
  55551. for (var count = 0; count < this._capacity; count++) {
  55552. indices.push(index);
  55553. indices.push(index + 1);
  55554. indices.push(index + 2);
  55555. indices.push(index);
  55556. indices.push(index + 2);
  55557. indices.push(index + 3);
  55558. index += 4;
  55559. }
  55560. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55561. };
  55562. /**
  55563. * Gets the maximum number of particles active at the same time.
  55564. * @returns The max number of active particles.
  55565. */
  55566. ParticleSystem.prototype.getCapacity = function () {
  55567. return this._capacity;
  55568. };
  55569. /**
  55570. * Gets Wether there are still active particles in the system.
  55571. * @returns True if it is alive, otherwise false.
  55572. */
  55573. ParticleSystem.prototype.isAlive = function () {
  55574. return this._alive;
  55575. };
  55576. /**
  55577. * Gets Wether the system has been started.
  55578. * @returns True if it has been started, otherwise false.
  55579. */
  55580. ParticleSystem.prototype.isStarted = function () {
  55581. return this._started;
  55582. };
  55583. /**
  55584. * Starts the particle system and begins to emit.
  55585. */
  55586. ParticleSystem.prototype.start = function () {
  55587. this._started = true;
  55588. this._stopped = false;
  55589. this._actualFrame = 0;
  55590. if (this.subEmitters && this.subEmitters.length != 0) {
  55591. this.activeSubSystems = new Array();
  55592. }
  55593. if (this.preWarmCycles) {
  55594. for (var index = 0; index < this.preWarmCycles; index++) {
  55595. this.animate(true);
  55596. }
  55597. }
  55598. };
  55599. /**
  55600. * Stops the particle system.
  55601. * @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.
  55602. */
  55603. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55604. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55605. this._stopped = true;
  55606. if (stopSubEmitters) {
  55607. this._stopSubEmitters();
  55608. }
  55609. };
  55610. // animation sheet
  55611. /**
  55612. * Remove all active particles
  55613. */
  55614. ParticleSystem.prototype.reset = function () {
  55615. this._stockParticles = [];
  55616. this._particles = [];
  55617. };
  55618. /**
  55619. * @hidden (for internal use only)
  55620. */
  55621. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55622. var offset = index * this._vertexBufferSize;
  55623. this._vertexData[offset++] = particle.position.x;
  55624. this._vertexData[offset++] = particle.position.y;
  55625. this._vertexData[offset++] = particle.position.z;
  55626. this._vertexData[offset++] = particle.color.r;
  55627. this._vertexData[offset++] = particle.color.g;
  55628. this._vertexData[offset++] = particle.color.b;
  55629. this._vertexData[offset++] = particle.color.a;
  55630. this._vertexData[offset++] = particle.angle;
  55631. this._vertexData[offset++] = particle.scale.x * particle.size;
  55632. this._vertexData[offset++] = particle.scale.y * particle.size;
  55633. if (this._isAnimationSheetEnabled) {
  55634. this._vertexData[offset++] = particle.cellIndex;
  55635. }
  55636. if (!this._isBillboardBased) {
  55637. if (particle._initialDirection) {
  55638. this._vertexData[offset++] = particle._initialDirection.x;
  55639. this._vertexData[offset++] = particle._initialDirection.y;
  55640. this._vertexData[offset++] = particle._initialDirection.z;
  55641. }
  55642. else {
  55643. this._vertexData[offset++] = particle.direction.x;
  55644. this._vertexData[offset++] = particle.direction.y;
  55645. this._vertexData[offset++] = particle.direction.z;
  55646. }
  55647. }
  55648. if (!this._useInstancing) {
  55649. if (this._isAnimationSheetEnabled) {
  55650. if (offsetX === 0)
  55651. offsetX = this._epsilon;
  55652. else if (offsetX === 1)
  55653. offsetX = 1 - this._epsilon;
  55654. if (offsetY === 0)
  55655. offsetY = this._epsilon;
  55656. else if (offsetY === 1)
  55657. offsetY = 1 - this._epsilon;
  55658. }
  55659. this._vertexData[offset++] = offsetX;
  55660. this._vertexData[offset++] = offsetY;
  55661. }
  55662. };
  55663. ParticleSystem.prototype._stopSubEmitters = function () {
  55664. if (!this.activeSubSystems) {
  55665. return;
  55666. }
  55667. this.activeSubSystems.forEach(function (subSystem) {
  55668. subSystem.stop(true);
  55669. });
  55670. this.activeSubSystems = new Array();
  55671. };
  55672. ParticleSystem.prototype._removeFromRoot = function () {
  55673. if (!this._rootParticleSystem) {
  55674. return;
  55675. }
  55676. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55677. if (index !== -1) {
  55678. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55679. }
  55680. };
  55681. // end of sub system methods
  55682. ParticleSystem.prototype._update = function (newParticles) {
  55683. // Update current
  55684. this._alive = this._particles.length > 0;
  55685. this.updateFunction(this._particles);
  55686. // Add new ones
  55687. var worldMatrix;
  55688. if (this.emitter.position) {
  55689. var emitterMesh = this.emitter;
  55690. worldMatrix = emitterMesh.getWorldMatrix();
  55691. }
  55692. else {
  55693. var emitterPosition = this.emitter;
  55694. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55695. }
  55696. var particle;
  55697. for (var index = 0; index < newParticles; index++) {
  55698. if (this._particles.length === this._capacity) {
  55699. break;
  55700. }
  55701. particle = this._createParticle();
  55702. this._particles.push(particle);
  55703. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55704. if (this.startPositionFunction) {
  55705. this.startPositionFunction(worldMatrix, particle.position, particle);
  55706. }
  55707. else {
  55708. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55709. }
  55710. if (this.startDirectionFunction) {
  55711. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  55712. }
  55713. else {
  55714. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55715. }
  55716. if (emitPower === 0) {
  55717. if (!particle._initialDirection) {
  55718. particle._initialDirection = particle.direction.clone();
  55719. }
  55720. else {
  55721. particle._initialDirection.copyFrom(particle.direction);
  55722. }
  55723. }
  55724. else {
  55725. particle._initialDirection = null;
  55726. }
  55727. particle.direction.scaleInPlace(emitPower);
  55728. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55729. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55730. particle._initialSize = particle.size;
  55731. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55732. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55733. particle.angle = BABYLON.Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  55734. if (!this._colorGradients || this._colorGradients.length === 0) {
  55735. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55736. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55737. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55738. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55739. }
  55740. else {
  55741. particle._currentColorGradient = this._colorGradients[0];
  55742. particle._currentColorGradient.getColorToRef(particle.color);
  55743. particle._currentColor1.copyFrom(particle.color);
  55744. if (this._colorGradients.length > 1) {
  55745. this._colorGradients[1].getColorToRef(particle._currentColor2);
  55746. }
  55747. else {
  55748. particle._currentColor2.copyFrom(particle.color);
  55749. }
  55750. }
  55751. }
  55752. };
  55753. /** @hidden */
  55754. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55755. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55756. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55757. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55758. if (isAnimationSheetEnabled) {
  55759. attributeNamesOrOptions.push("cellIndex");
  55760. }
  55761. if (!isBillboardBased) {
  55762. attributeNamesOrOptions.push("direction");
  55763. }
  55764. return attributeNamesOrOptions;
  55765. };
  55766. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55767. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55768. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55769. if (isAnimationSheetEnabled) {
  55770. effectCreationOption.push("particlesInfos");
  55771. }
  55772. return effectCreationOption;
  55773. };
  55774. ParticleSystem.prototype._getEffect = function () {
  55775. if (this._customEffect) {
  55776. return this._customEffect;
  55777. }
  55778. ;
  55779. var defines = [];
  55780. if (this._scene.clipPlane) {
  55781. defines.push("#define CLIPPLANE");
  55782. }
  55783. if (this._isAnimationSheetEnabled) {
  55784. defines.push("#define ANIMATESHEET");
  55785. }
  55786. if (this._isBillboardBased) {
  55787. defines.push("#define BILLBOARD");
  55788. }
  55789. // Effect
  55790. var join = defines.join("\n");
  55791. if (this._cachedDefines !== join) {
  55792. this._cachedDefines = join;
  55793. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55794. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55795. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55796. }
  55797. return this._effect;
  55798. };
  55799. /**
  55800. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55801. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55802. */
  55803. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55804. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55805. if (!this._started)
  55806. return;
  55807. if (!preWarmOnly) {
  55808. var effect = this._getEffect();
  55809. // Check
  55810. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55811. return;
  55812. if (this._currentRenderId === this._scene.getRenderId()) {
  55813. return;
  55814. }
  55815. this._currentRenderId = this._scene.getRenderId();
  55816. }
  55817. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55818. // determine the number of particles we need to create
  55819. var newParticles;
  55820. if (this.manualEmitCount > -1) {
  55821. newParticles = this.manualEmitCount;
  55822. this._newPartsExcess = 0;
  55823. this.manualEmitCount = 0;
  55824. }
  55825. else {
  55826. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55827. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55828. }
  55829. if (this._newPartsExcess > 1.0) {
  55830. newParticles += this._newPartsExcess >> 0;
  55831. this._newPartsExcess -= this._newPartsExcess >> 0;
  55832. }
  55833. this._alive = false;
  55834. if (!this._stopped) {
  55835. this._actualFrame += this._scaledUpdateSpeed;
  55836. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55837. this.stop();
  55838. }
  55839. else {
  55840. newParticles = 0;
  55841. }
  55842. this._update(newParticles);
  55843. // Stopped?
  55844. if (this._stopped) {
  55845. if (!this._alive) {
  55846. this._started = false;
  55847. if (this.onAnimationEnd) {
  55848. this.onAnimationEnd();
  55849. }
  55850. if (this.disposeOnStop) {
  55851. this._scene._toBeDisposed.push(this);
  55852. }
  55853. }
  55854. }
  55855. if (!preWarmOnly) {
  55856. // Update VBO
  55857. var offset = 0;
  55858. for (var index = 0; index < this._particles.length; index++) {
  55859. var particle = this._particles[index];
  55860. this._appendParticleVertices(offset, particle);
  55861. offset += this._useInstancing ? 1 : 4;
  55862. }
  55863. if (this._vertexBuffer) {
  55864. this._vertexBuffer.update(this._vertexData);
  55865. }
  55866. }
  55867. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55868. this.stop();
  55869. }
  55870. };
  55871. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55872. this._appendParticleVertex(offset++, particle, 0, 0);
  55873. if (!this._useInstancing) {
  55874. this._appendParticleVertex(offset++, particle, 1, 0);
  55875. this._appendParticleVertex(offset++, particle, 1, 1);
  55876. this._appendParticleVertex(offset++, particle, 0, 1);
  55877. }
  55878. };
  55879. /**
  55880. * Rebuilds the particle system.
  55881. */
  55882. ParticleSystem.prototype.rebuild = function () {
  55883. this._createIndexBuffer();
  55884. if (this._vertexBuffer) {
  55885. this._vertexBuffer._rebuild();
  55886. }
  55887. };
  55888. /**
  55889. * Is this system ready to be used/rendered
  55890. * @return true if the system is ready
  55891. */
  55892. ParticleSystem.prototype.isReady = function () {
  55893. var effect = this._getEffect();
  55894. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55895. return false;
  55896. }
  55897. return true;
  55898. };
  55899. /**
  55900. * Renders the particle system in its current state.
  55901. * @returns the current number of particles
  55902. */
  55903. ParticleSystem.prototype.render = function () {
  55904. var effect = this._getEffect();
  55905. // Check
  55906. if (!this.isReady() || !this._particles.length) {
  55907. return 0;
  55908. }
  55909. var engine = this._scene.getEngine();
  55910. // Render
  55911. engine.enableEffect(effect);
  55912. engine.setState(false);
  55913. var viewMatrix = this._scene.getViewMatrix();
  55914. effect.setTexture("diffuseSampler", this.particleTexture);
  55915. effect.setMatrix("view", viewMatrix);
  55916. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55917. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55918. var baseSize = this.particleTexture.getBaseSize();
  55919. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55920. }
  55921. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55922. if (this._scene.clipPlane) {
  55923. var clipPlane = this._scene.clipPlane;
  55924. var invView = viewMatrix.clone();
  55925. invView.invert();
  55926. effect.setMatrix("invView", invView);
  55927. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55928. }
  55929. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55930. // Draw order
  55931. switch (this.blendMode) {
  55932. case ParticleSystem.BLENDMODE_ADD:
  55933. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55934. break;
  55935. case ParticleSystem.BLENDMODE_ONEONE:
  55936. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55937. break;
  55938. case ParticleSystem.BLENDMODE_STANDARD:
  55939. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55940. break;
  55941. }
  55942. if (this.forceDepthWrite) {
  55943. engine.setDepthWrite(true);
  55944. }
  55945. if (this._useInstancing) {
  55946. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55947. engine.unbindInstanceAttributes();
  55948. }
  55949. else {
  55950. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55951. }
  55952. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55953. return this._particles.length;
  55954. };
  55955. /**
  55956. * Disposes the particle system and free the associated resources
  55957. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55958. */
  55959. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55960. if (disposeTexture === void 0) { disposeTexture = true; }
  55961. if (this._vertexBuffer) {
  55962. this._vertexBuffer.dispose();
  55963. this._vertexBuffer = null;
  55964. }
  55965. if (this._spriteBuffer) {
  55966. this._spriteBuffer.dispose();
  55967. this._spriteBuffer = null;
  55968. }
  55969. if (this._indexBuffer) {
  55970. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55971. this._indexBuffer = null;
  55972. }
  55973. if (disposeTexture && this.particleTexture) {
  55974. this.particleTexture.dispose();
  55975. this.particleTexture = null;
  55976. }
  55977. this._removeFromRoot();
  55978. // Remove from scene
  55979. var index = this._scene.particleSystems.indexOf(this);
  55980. if (index > -1) {
  55981. this._scene.particleSystems.splice(index, 1);
  55982. }
  55983. // Callback
  55984. this.onDisposeObservable.notifyObservers(this);
  55985. this.onDisposeObservable.clear();
  55986. };
  55987. /**
  55988. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55989. * @param radius The radius of the sphere to emit from
  55990. * @returns the emitter
  55991. */
  55992. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55993. if (radius === void 0) { radius = 1; }
  55994. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55995. this.particleEmitterType = particleEmitter;
  55996. return particleEmitter;
  55997. };
  55998. /**
  55999. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56000. * @param radius The radius of the sphere to emit from
  56001. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56002. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56003. * @returns the emitter
  56004. */
  56005. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56006. if (radius === void 0) { radius = 1; }
  56007. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56008. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56009. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56010. this.particleEmitterType = particleEmitter;
  56011. return particleEmitter;
  56012. };
  56013. /**
  56014. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56015. * @param radius The radius of the cone to emit from
  56016. * @param angle The base angle of the cone
  56017. * @returns the emitter
  56018. */
  56019. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56020. if (radius === void 0) { radius = 1; }
  56021. if (angle === void 0) { angle = Math.PI / 4; }
  56022. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56023. this.particleEmitterType = particleEmitter;
  56024. return particleEmitter;
  56025. };
  56026. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56027. /**
  56028. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56029. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56030. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56031. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56032. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56033. * @returns the emitter
  56034. */
  56035. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56036. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56037. this.particleEmitterType = particleEmitter;
  56038. this.direction1 = direction1;
  56039. this.direction2 = direction2;
  56040. this.minEmitBox = minEmitBox;
  56041. this.maxEmitBox = maxEmitBox;
  56042. return particleEmitter;
  56043. };
  56044. // Clone
  56045. /**
  56046. * Clones the particle system.
  56047. * @param name The name of the cloned object
  56048. * @param newEmitter The new emitter to use
  56049. * @returns the cloned particle system
  56050. */
  56051. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56052. var custom = null;
  56053. var program = null;
  56054. if (this.customShader != null) {
  56055. program = this.customShader;
  56056. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56057. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56058. }
  56059. else if (this._customEffect) {
  56060. custom = this._customEffect;
  56061. }
  56062. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56063. result.customShader = program;
  56064. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56065. if (newEmitter === undefined) {
  56066. newEmitter = this.emitter;
  56067. }
  56068. result.emitter = newEmitter;
  56069. if (this.particleTexture) {
  56070. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56071. }
  56072. if (!this.preventAutoStart) {
  56073. result.start();
  56074. }
  56075. return result;
  56076. };
  56077. /**
  56078. * Serializes the particle system to a JSON object.
  56079. * @returns the JSON object
  56080. */
  56081. ParticleSystem.prototype.serialize = function () {
  56082. var serializationObject = {};
  56083. ParticleSystem._Serialize(serializationObject, this);
  56084. serializationObject.textureMask = this.textureMask.asArray();
  56085. serializationObject.customShader = this.customShader;
  56086. serializationObject.preventAutoStart = this.preventAutoStart;
  56087. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56088. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56089. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56090. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56091. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56092. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56093. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56094. return serializationObject;
  56095. };
  56096. /** @hidden */
  56097. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56098. serializationObject.name = particleSystem.name;
  56099. serializationObject.id = particleSystem.id;
  56100. serializationObject.capacity = particleSystem.getCapacity();
  56101. // Emitter
  56102. if (particleSystem.emitter.position) {
  56103. var emitterMesh = particleSystem.emitter;
  56104. serializationObject.emitterId = emitterMesh.id;
  56105. }
  56106. else {
  56107. var emitterPosition = particleSystem.emitter;
  56108. serializationObject.emitter = emitterPosition.asArray();
  56109. }
  56110. // Emitter
  56111. if (particleSystem.particleEmitterType) {
  56112. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56113. }
  56114. if (particleSystem.particleTexture) {
  56115. serializationObject.textureName = particleSystem.particleTexture.name;
  56116. }
  56117. // Animations
  56118. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56119. // Particle system
  56120. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56121. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56122. serializationObject.minSize = particleSystem.minSize;
  56123. serializationObject.maxSize = particleSystem.maxSize;
  56124. serializationObject.minScaleX = particleSystem.minScaleX;
  56125. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56126. serializationObject.minScaleY = particleSystem.minScaleY;
  56127. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56128. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56129. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56130. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56131. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56132. serializationObject.emitRate = particleSystem.emitRate;
  56133. serializationObject.gravity = particleSystem.gravity.asArray();
  56134. serializationObject.color1 = particleSystem.color1.asArray();
  56135. serializationObject.color2 = particleSystem.color2.asArray();
  56136. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56137. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56138. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56139. serializationObject.blendMode = particleSystem.blendMode;
  56140. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56141. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56142. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56143. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56144. var colorGradients = particleSystem.getColorGradients();
  56145. if (colorGradients) {
  56146. serializationObject.colorGradients = [];
  56147. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56148. var colorGradient = colorGradients_1[_i];
  56149. var serializedGradient = {
  56150. gradient: colorGradient.gradient,
  56151. color1: colorGradient.color1.asArray()
  56152. };
  56153. if (colorGradient.color2) {
  56154. serializedGradient.color2 = colorGradient.color2.asArray();
  56155. }
  56156. serializationObject.colorGradients.push(serializedGradient);
  56157. }
  56158. }
  56159. var sizeGradients = particleSystem.getSizeGradients();
  56160. if (sizeGradients) {
  56161. serializationObject.sizeGradients = [];
  56162. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56163. var sizeGradient = sizeGradients_1[_a];
  56164. serializationObject.sizeGradients.push({
  56165. gradient: sizeGradient.gradient,
  56166. factor: sizeGradient.factor
  56167. });
  56168. }
  56169. }
  56170. };
  56171. /** @hidden */
  56172. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56173. // Texture
  56174. if (parsedParticleSystem.textureName) {
  56175. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56176. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56177. }
  56178. // Emitter
  56179. if (parsedParticleSystem.emitterId) {
  56180. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56181. }
  56182. else {
  56183. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56184. }
  56185. // Animations
  56186. if (parsedParticleSystem.animations) {
  56187. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56188. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56189. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56190. }
  56191. }
  56192. if (parsedParticleSystem.autoAnimate) {
  56193. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56194. }
  56195. // Particle system
  56196. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56197. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56198. particleSystem.minSize = parsedParticleSystem.minSize;
  56199. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56200. if (parsedParticleSystem.minScaleX) {
  56201. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56202. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56203. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56204. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56205. }
  56206. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56207. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56208. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56209. }
  56210. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56211. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56212. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56213. }
  56214. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56215. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56216. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56217. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56218. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56219. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56220. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56221. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56222. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56223. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56224. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56225. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56226. if (parsedParticleSystem.colorGradients) {
  56227. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56228. var colorGradient = _a[_i];
  56229. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56230. }
  56231. }
  56232. if (parsedParticleSystem.sizeGradients) {
  56233. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56234. var sizeGradient = _c[_b];
  56235. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor);
  56236. }
  56237. }
  56238. // Emitter
  56239. var emitterType;
  56240. if (parsedParticleSystem.particleEmitterType) {
  56241. switch (parsedParticleSystem.particleEmitterType.type) {
  56242. case "SphereEmitter":
  56243. emitterType = new BABYLON.SphereParticleEmitter();
  56244. break;
  56245. case "SphereDirectedParticleEmitter":
  56246. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56247. break;
  56248. case "ConeEmitter":
  56249. emitterType = new BABYLON.ConeParticleEmitter();
  56250. break;
  56251. case "BoxEmitter":
  56252. default:
  56253. emitterType = new BABYLON.BoxParticleEmitter();
  56254. break;
  56255. }
  56256. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56257. }
  56258. else {
  56259. emitterType = new BABYLON.BoxParticleEmitter();
  56260. emitterType.parse(parsedParticleSystem);
  56261. }
  56262. particleSystem.particleEmitterType = emitterType;
  56263. };
  56264. /**
  56265. * Parses a JSON object to create a particle system.
  56266. * @param parsedParticleSystem The JSON object to parse
  56267. * @param scene The scene to create the particle system in
  56268. * @param rootUrl The root url to use to load external dependencies like texture
  56269. * @returns the Parsed particle system
  56270. */
  56271. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56272. var name = parsedParticleSystem.name;
  56273. var custom = null;
  56274. var program = null;
  56275. if (parsedParticleSystem.customShader) {
  56276. program = parsedParticleSystem.customShader;
  56277. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56278. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56279. }
  56280. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56281. particleSystem.customShader = program;
  56282. if (parsedParticleSystem.id) {
  56283. particleSystem.id = parsedParticleSystem.id;
  56284. }
  56285. // Auto start
  56286. if (parsedParticleSystem.preventAutoStart) {
  56287. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56288. }
  56289. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56290. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56291. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56292. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56293. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56294. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56295. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56296. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56297. if (!particleSystem.preventAutoStart) {
  56298. particleSystem.start();
  56299. }
  56300. return particleSystem;
  56301. };
  56302. /**
  56303. * Source color is added to the destination color without alpha affecting the result.
  56304. */
  56305. ParticleSystem.BLENDMODE_ONEONE = 0;
  56306. /**
  56307. * Blend current color and particle color using particle’s alpha.
  56308. */
  56309. ParticleSystem.BLENDMODE_STANDARD = 1;
  56310. /**
  56311. * Add current color and particle color multiplied by particle’s alpha.
  56312. */
  56313. ParticleSystem.BLENDMODE_ADD = 2;
  56314. return ParticleSystem;
  56315. }());
  56316. BABYLON.ParticleSystem = ParticleSystem;
  56317. })(BABYLON || (BABYLON = {}));
  56318. //# sourceMappingURL=babylon.particleSystem.js.map
  56319. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56320. var BABYLON;
  56321. (function (BABYLON) {
  56322. /**
  56323. * Particle emitter emitting particles from the inside of a box.
  56324. * It emits the particles randomly between 2 given directions.
  56325. */
  56326. var BoxParticleEmitter = /** @class */ (function () {
  56327. /**
  56328. * Creates a new instance BoxParticleEmitter
  56329. */
  56330. function BoxParticleEmitter() {
  56331. /**
  56332. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56333. */
  56334. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56335. /**
  56336. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56337. */
  56338. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56339. /**
  56340. * 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.
  56341. */
  56342. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56343. /**
  56344. * 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.
  56345. */
  56346. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56347. }
  56348. /**
  56349. * Called by the particle System when the direction is computed for the created particle.
  56350. * @param worldMatrix is the world matrix of the particle system
  56351. * @param directionToUpdate is the direction vector to update with the result
  56352. * @param particle is the particle we are computed the direction for
  56353. */
  56354. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56355. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56356. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56357. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56358. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56359. };
  56360. /**
  56361. * Called by the particle System when the position is computed for the created particle.
  56362. * @param worldMatrix is the world matrix of the particle system
  56363. * @param positionToUpdate is the position vector to update with the result
  56364. * @param particle is the particle we are computed the position for
  56365. */
  56366. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56367. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56368. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56369. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56370. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56371. };
  56372. /**
  56373. * Clones the current emitter and returns a copy of it
  56374. * @returns the new emitter
  56375. */
  56376. BoxParticleEmitter.prototype.clone = function () {
  56377. var newOne = new BoxParticleEmitter();
  56378. BABYLON.Tools.DeepCopy(this, newOne);
  56379. return newOne;
  56380. };
  56381. /**
  56382. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56383. * @param effect defines the update shader
  56384. */
  56385. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56386. effect.setVector3("direction1", this.direction1);
  56387. effect.setVector3("direction2", this.direction2);
  56388. effect.setVector3("minEmitBox", this.minEmitBox);
  56389. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56390. };
  56391. /**
  56392. * Returns a string to use to update the GPU particles update shader
  56393. * @returns a string containng the defines string
  56394. */
  56395. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56396. return "#define BOXEMITTER";
  56397. };
  56398. /**
  56399. * Returns the string "BoxEmitter"
  56400. * @returns a string containing the class name
  56401. */
  56402. BoxParticleEmitter.prototype.getClassName = function () {
  56403. return "BoxEmitter";
  56404. };
  56405. /**
  56406. * Serializes the particle system to a JSON object.
  56407. * @returns the JSON object
  56408. */
  56409. BoxParticleEmitter.prototype.serialize = function () {
  56410. var serializationObject = {};
  56411. serializationObject.type = this.getClassName();
  56412. serializationObject.direction1 = this.direction1.asArray();
  56413. serializationObject.direction2 = this.direction2.asArray();
  56414. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56415. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56416. return serializationObject;
  56417. };
  56418. /**
  56419. * Parse properties from a JSON object
  56420. * @param serializationObject defines the JSON object
  56421. */
  56422. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56423. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56424. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56425. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56426. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56427. };
  56428. return BoxParticleEmitter;
  56429. }());
  56430. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56431. })(BABYLON || (BABYLON = {}));
  56432. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56433. var BABYLON;
  56434. (function (BABYLON) {
  56435. /**
  56436. * Particle emitter emitting particles from the inside of a cone.
  56437. * It emits the particles alongside the cone volume from the base to the particle.
  56438. * The emission direction might be randomized.
  56439. */
  56440. var ConeParticleEmitter = /** @class */ (function () {
  56441. /**
  56442. * Creates a new instance ConeParticleEmitter
  56443. * @param radius the radius of the emission cone (1 by default)
  56444. * @param angles the cone base angle (PI by default)
  56445. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56446. */
  56447. function ConeParticleEmitter(radius, angle,
  56448. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56449. directionRandomizer) {
  56450. if (radius === void 0) { radius = 1; }
  56451. if (angle === void 0) { angle = Math.PI; }
  56452. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56453. this.directionRandomizer = directionRandomizer;
  56454. this.angle = angle;
  56455. this.radius = radius;
  56456. }
  56457. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56458. /**
  56459. * Gets or sets the radius of the emission cone
  56460. */
  56461. get: function () {
  56462. return this._radius;
  56463. },
  56464. set: function (value) {
  56465. this._radius = value;
  56466. this._buildHeight();
  56467. },
  56468. enumerable: true,
  56469. configurable: true
  56470. });
  56471. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56472. /**
  56473. * Gets or sets the angle of the emission cone
  56474. */
  56475. get: function () {
  56476. return this._angle;
  56477. },
  56478. set: function (value) {
  56479. this._angle = value;
  56480. this._buildHeight();
  56481. },
  56482. enumerable: true,
  56483. configurable: true
  56484. });
  56485. ConeParticleEmitter.prototype._buildHeight = function () {
  56486. if (this._angle !== 0) {
  56487. this._height = this._radius / Math.tan(this._angle / 2);
  56488. }
  56489. else {
  56490. this._height = 1;
  56491. }
  56492. };
  56493. /**
  56494. * Called by the particle System when the direction is computed for the created particle.
  56495. * @param worldMatrix is the world matrix of the particle system
  56496. * @param directionToUpdate is the direction vector to update with the result
  56497. * @param particle is the particle we are computed the direction for
  56498. */
  56499. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56500. if (this._angle === 0) {
  56501. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56502. }
  56503. else {
  56504. // measure the direction Vector from the emitter to the particle.
  56505. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56506. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56507. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56508. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56509. direction.x += randX;
  56510. direction.y += randY;
  56511. direction.z += randZ;
  56512. direction.normalize();
  56513. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56514. }
  56515. };
  56516. /**
  56517. * Called by the particle System when the position is computed for the created particle.
  56518. * @param worldMatrix is the world matrix of the particle system
  56519. * @param positionToUpdate is the position vector to update with the result
  56520. * @param particle is the particle we are computed the position for
  56521. */
  56522. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56523. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56524. var h = BABYLON.Scalar.RandomRange(0, 1);
  56525. // Better distribution in a cone at normal angles.
  56526. h = 1 - h * h;
  56527. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56528. radius = radius * h;
  56529. var randX = radius * Math.sin(s);
  56530. var randZ = radius * Math.cos(s);
  56531. var randY = h * this._height;
  56532. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56533. };
  56534. /**
  56535. * Clones the current emitter and returns a copy of it
  56536. * @returns the new emitter
  56537. */
  56538. ConeParticleEmitter.prototype.clone = function () {
  56539. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56540. BABYLON.Tools.DeepCopy(this, newOne);
  56541. return newOne;
  56542. };
  56543. /**
  56544. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56545. * @param effect defines the update shader
  56546. */
  56547. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56548. effect.setFloat("radius", this._radius);
  56549. effect.setFloat("coneAngle", this._angle);
  56550. effect.setFloat("height", this._height);
  56551. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56552. };
  56553. /**
  56554. * Returns a string to use to update the GPU particles update shader
  56555. * @returns a string containng the defines string
  56556. */
  56557. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56558. return "#define CONEEMITTER";
  56559. };
  56560. /**
  56561. * Returns the string "BoxEmitter"
  56562. * @returns a string containing the class name
  56563. */
  56564. ConeParticleEmitter.prototype.getClassName = function () {
  56565. return "ConeEmitter";
  56566. };
  56567. /**
  56568. * Serializes the particle system to a JSON object.
  56569. * @returns the JSON object
  56570. */
  56571. ConeParticleEmitter.prototype.serialize = function () {
  56572. var serializationObject = {};
  56573. serializationObject.type = this.getClassName();
  56574. serializationObject.radius = this._radius;
  56575. serializationObject.angle = this._angle;
  56576. serializationObject.directionRandomizer = this.directionRandomizer;
  56577. return serializationObject;
  56578. };
  56579. /**
  56580. * Parse properties from a JSON object
  56581. * @param serializationObject defines the JSON object
  56582. */
  56583. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56584. this.radius = serializationObject.radius;
  56585. this.angle = serializationObject.angle;
  56586. this.directionRandomizer = serializationObject.directionRandomizer;
  56587. };
  56588. return ConeParticleEmitter;
  56589. }());
  56590. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56591. })(BABYLON || (BABYLON = {}));
  56592. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56593. var BABYLON;
  56594. (function (BABYLON) {
  56595. /**
  56596. * Particle emitter emitting particles from the inside of a sphere.
  56597. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56598. */
  56599. var SphereParticleEmitter = /** @class */ (function () {
  56600. /**
  56601. * Creates a new instance SphereParticleEmitter
  56602. * @param radius the radius of the emission sphere (1 by default)
  56603. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56604. */
  56605. function SphereParticleEmitter(
  56606. /**
  56607. * The radius of the emission sphere.
  56608. */
  56609. radius,
  56610. /**
  56611. * How much to randomize the particle direction [0-1].
  56612. */
  56613. directionRandomizer) {
  56614. if (radius === void 0) { radius = 1; }
  56615. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56616. this.radius = radius;
  56617. this.directionRandomizer = directionRandomizer;
  56618. /**
  56619. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56620. */
  56621. this.radiusRange = 1;
  56622. }
  56623. /**
  56624. * Called by the particle System when the direction is computed for the created particle.
  56625. * @param worldMatrix is the world matrix of the particle system
  56626. * @param directionToUpdate is the direction vector to update with the result
  56627. * @param particle is the particle we are computed the direction for
  56628. */
  56629. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56630. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56631. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56632. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56633. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56634. direction.x += randX;
  56635. direction.y += randY;
  56636. direction.z += randZ;
  56637. direction.normalize();
  56638. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56639. };
  56640. /**
  56641. * Called by the particle System when the position is computed for the created particle.
  56642. * @param worldMatrix is the world matrix of the particle system
  56643. * @param positionToUpdate is the position vector to update with the result
  56644. * @param particle is the particle we are computed the position for
  56645. */
  56646. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56647. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56648. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56649. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56650. var theta = Math.acos(2 * v - 1);
  56651. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56652. var randY = randRadius * Math.cos(theta);
  56653. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56654. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56655. };
  56656. /**
  56657. * Clones the current emitter and returns a copy of it
  56658. * @returns the new emitter
  56659. */
  56660. SphereParticleEmitter.prototype.clone = function () {
  56661. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56662. BABYLON.Tools.DeepCopy(this, newOne);
  56663. return newOne;
  56664. };
  56665. /**
  56666. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56667. * @param effect defines the update shader
  56668. */
  56669. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56670. effect.setFloat("radius", this.radius);
  56671. effect.setFloat("radiusRange", this.radiusRange);
  56672. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56673. };
  56674. /**
  56675. * Returns a string to use to update the GPU particles update shader
  56676. * @returns a string containng the defines string
  56677. */
  56678. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56679. return "#define SPHEREEMITTER";
  56680. };
  56681. /**
  56682. * Returns the string "SphereParticleEmitter"
  56683. * @returns a string containing the class name
  56684. */
  56685. SphereParticleEmitter.prototype.getClassName = function () {
  56686. return "SphereParticleEmitter";
  56687. };
  56688. /**
  56689. * Serializes the particle system to a JSON object.
  56690. * @returns the JSON object
  56691. */
  56692. SphereParticleEmitter.prototype.serialize = function () {
  56693. var serializationObject = {};
  56694. serializationObject.type = this.getClassName();
  56695. serializationObject.radius = this.radius;
  56696. serializationObject.directionRandomizer = this.directionRandomizer;
  56697. return serializationObject;
  56698. };
  56699. /**
  56700. * Parse properties from a JSON object
  56701. * @param serializationObject defines the JSON object
  56702. */
  56703. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56704. this.radius = serializationObject.radius;
  56705. this.directionRandomizer = serializationObject.directionRandomizer;
  56706. };
  56707. return SphereParticleEmitter;
  56708. }());
  56709. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56710. /**
  56711. * Particle emitter emitting particles from the inside of a sphere.
  56712. * It emits the particles randomly between two vectors.
  56713. */
  56714. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56715. __extends(SphereDirectedParticleEmitter, _super);
  56716. /**
  56717. * Creates a new instance SphereDirectedParticleEmitter
  56718. * @param radius the radius of the emission sphere (1 by default)
  56719. * @param direction1 the min limit of the emission direction (up vector by default)
  56720. * @param direction2 the max limit of the emission direction (up vector by default)
  56721. */
  56722. function SphereDirectedParticleEmitter(radius,
  56723. /**
  56724. * The min limit of the emission direction.
  56725. */
  56726. direction1,
  56727. /**
  56728. * The max limit of the emission direction.
  56729. */
  56730. direction2) {
  56731. if (radius === void 0) { radius = 1; }
  56732. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56733. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56734. var _this = _super.call(this, radius) || this;
  56735. _this.direction1 = direction1;
  56736. _this.direction2 = direction2;
  56737. return _this;
  56738. }
  56739. /**
  56740. * Called by the particle System when the direction is computed for the created particle.
  56741. * @param worldMatrix is the world matrix of the particle system
  56742. * @param directionToUpdate is the direction vector to update with the result
  56743. * @param particle is the particle we are computed the direction for
  56744. */
  56745. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56746. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56747. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56748. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56749. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56750. };
  56751. /**
  56752. * Clones the current emitter and returns a copy of it
  56753. * @returns the new emitter
  56754. */
  56755. SphereDirectedParticleEmitter.prototype.clone = function () {
  56756. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56757. BABYLON.Tools.DeepCopy(this, newOne);
  56758. return newOne;
  56759. };
  56760. /**
  56761. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56762. * @param effect defines the update shader
  56763. */
  56764. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56765. effect.setFloat("radius", this.radius);
  56766. effect.setFloat("radiusRange", this.radiusRange);
  56767. effect.setVector3("direction1", this.direction1);
  56768. effect.setVector3("direction2", this.direction2);
  56769. };
  56770. /**
  56771. * Returns a string to use to update the GPU particles update shader
  56772. * @returns a string containng the defines string
  56773. */
  56774. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56775. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56776. };
  56777. /**
  56778. * Returns the string "SphereDirectedParticleEmitter"
  56779. * @returns a string containing the class name
  56780. */
  56781. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56782. return "SphereDirectedParticleEmitter";
  56783. };
  56784. /**
  56785. * Serializes the particle system to a JSON object.
  56786. * @returns the JSON object
  56787. */
  56788. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56789. var serializationObject = _super.prototype.serialize.call(this);
  56790. serializationObject.direction1 = this.direction1.asArray();
  56791. serializationObject.direction2 = this.direction2.asArray();
  56792. return serializationObject;
  56793. };
  56794. /**
  56795. * Parse properties from a JSON object
  56796. * @param serializationObject defines the JSON object
  56797. */
  56798. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56799. _super.prototype.parse.call(this, serializationObject);
  56800. this.direction1.copyFrom(serializationObject.direction1);
  56801. this.direction2.copyFrom(serializationObject.direction2);
  56802. };
  56803. return SphereDirectedParticleEmitter;
  56804. }(SphereParticleEmitter));
  56805. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56806. })(BABYLON || (BABYLON = {}));
  56807. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56808. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56809. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56810. s = arguments[i];
  56811. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56812. t[p] = s[p];
  56813. }
  56814. return t;
  56815. };
  56816. var BABYLON;
  56817. (function (BABYLON) {
  56818. /**
  56819. * This represents a GPU particle system in Babylon
  56820. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56821. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56822. */
  56823. var GPUParticleSystem = /** @class */ (function () {
  56824. /**
  56825. * Instantiates a GPU particle system.
  56826. * 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.
  56827. * @param name The name of the particle system
  56828. * @param capacity The max number of particles alive at the same time
  56829. * @param scene The scene the particle system belongs to
  56830. */
  56831. function GPUParticleSystem(name, options, scene) {
  56832. /**
  56833. * The emitter represents the Mesh or position we are attaching the particle system to.
  56834. */
  56835. this.emitter = null;
  56836. /**
  56837. * The rendering group used by the Particle system to chose when to render.
  56838. */
  56839. this.renderingGroupId = 0;
  56840. /**
  56841. * The layer mask we are rendering the particles through.
  56842. */
  56843. this.layerMask = 0x0FFFFFFF;
  56844. this._accumulatedCount = 0;
  56845. this._targetIndex = 0;
  56846. this._currentRenderId = -1;
  56847. this._started = false;
  56848. this._stopped = false;
  56849. this._timeDelta = 0;
  56850. this._attributesStrideSize = 21;
  56851. this._actualFrame = 0;
  56852. /**
  56853. * List of animations used by the particle system.
  56854. */
  56855. this.animations = [];
  56856. /**
  56857. * An event triggered when the system is disposed.
  56858. */
  56859. this.onDisposeObservable = new BABYLON.Observable();
  56860. /**
  56861. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56862. */
  56863. this.updateSpeed = 0.01;
  56864. /**
  56865. * The amount of time the particle system is running (depends of the overall update speed).
  56866. */
  56867. this.targetStopDuration = 0;
  56868. /**
  56869. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56870. */
  56871. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56872. /**
  56873. * Minimum life time of emitting particles.
  56874. */
  56875. this.minLifeTime = 1;
  56876. /**
  56877. * Maximum life time of emitting particles.
  56878. */
  56879. this.maxLifeTime = 1;
  56880. /**
  56881. * Minimum Size of emitting particles.
  56882. */
  56883. this.minSize = 1;
  56884. /**
  56885. * Maximum Size of emitting particles.
  56886. */
  56887. this.maxSize = 1;
  56888. /**
  56889. * Minimum scale of emitting particles on X axis.
  56890. */
  56891. this.minScaleX = 1;
  56892. /**
  56893. * Maximum scale of emitting particles on X axis.
  56894. */
  56895. this.maxScaleX = 1;
  56896. /**
  56897. * Minimum scale of emitting particles on Y axis.
  56898. */
  56899. this.minScaleY = 1;
  56900. /**
  56901. * Maximum scale of emitting particles on Y axis.
  56902. */
  56903. this.maxScaleY = 1;
  56904. /**
  56905. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56906. */
  56907. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56908. /**
  56909. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56910. */
  56911. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56912. /**
  56913. * Color the particle will have at the end of its lifetime.
  56914. */
  56915. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56916. /**
  56917. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56918. */
  56919. this.emitRate = 100;
  56920. /**
  56921. * You can use gravity if you want to give an orientation to your particles.
  56922. */
  56923. this.gravity = BABYLON.Vector3.Zero();
  56924. /**
  56925. * Minimum power of emitting particles.
  56926. */
  56927. this.minEmitPower = 1;
  56928. /**
  56929. * Maximum power of emitting particles.
  56930. */
  56931. this.maxEmitPower = 1;
  56932. /**
  56933. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56934. */
  56935. this.minAngularSpeed = 0;
  56936. /**
  56937. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56938. */
  56939. this.maxAngularSpeed = 0;
  56940. /**
  56941. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56942. * to override the particles.
  56943. */
  56944. this.forceDepthWrite = false;
  56945. this._preWarmDone = false;
  56946. /** 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 */
  56947. this.preWarmCycles = 0;
  56948. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56949. this.preWarmStepOffset = 1;
  56950. /**
  56951. * Gets or sets the minimal initial rotation in radians.
  56952. */
  56953. this.minInitialRotation = 0;
  56954. /**
  56955. * Gets or sets the maximal initial rotation in radians.
  56956. */
  56957. this.maxInitialRotation = 0;
  56958. this._isBillboardBased = true;
  56959. this._colorGradients = null;
  56960. this._sizeGradients = null;
  56961. this.id = name;
  56962. this.name = name;
  56963. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56964. this._engine = this._scene.getEngine();
  56965. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56966. var optionsAsNumber = options;
  56967. if (isFinite(optionsAsNumber)) {
  56968. fullOptions.capacity = optionsAsNumber;
  56969. }
  56970. this._capacity = fullOptions.capacity;
  56971. this._activeCount = fullOptions.capacity;
  56972. this._currentActiveCount = 0;
  56973. this._scene.particleSystems.push(this);
  56974. this._updateEffectOptions = {
  56975. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "initialSize"],
  56976. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56977. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56978. "angleRange", "radiusRange"],
  56979. uniformBuffersNames: [],
  56980. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler"],
  56981. defines: "",
  56982. fallbacks: null,
  56983. onCompiled: null,
  56984. onError: null,
  56985. indexParameters: null,
  56986. maxSimultaneousLights: 0,
  56987. transformFeedbackVaryings: []
  56988. };
  56989. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56990. // Random data
  56991. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56992. var d = [];
  56993. for (var i = 0; i < maxTextureSize; ++i) {
  56994. d.push(Math.random());
  56995. d.push(Math.random());
  56996. d.push(Math.random());
  56997. d.push(Math.random());
  56998. }
  56999. 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);
  57000. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57001. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57002. d = [];
  57003. for (var i = 0; i < maxTextureSize; ++i) {
  57004. d.push(Math.random());
  57005. d.push(Math.random());
  57006. d.push(Math.random());
  57007. d.push(Math.random());
  57008. }
  57009. 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);
  57010. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57011. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57012. this._randomTextureSize = maxTextureSize;
  57013. }
  57014. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57015. /**
  57016. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57017. */
  57018. get: function () {
  57019. if (!BABYLON.Engine.LastCreatedEngine) {
  57020. return false;
  57021. }
  57022. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57023. },
  57024. enumerable: true,
  57025. configurable: true
  57026. });
  57027. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57028. /**
  57029. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57030. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57031. */
  57032. get: function () {
  57033. if (this.particleEmitterType.direction1) {
  57034. return this.particleEmitterType.direction1;
  57035. }
  57036. return BABYLON.Vector3.Zero();
  57037. },
  57038. set: function (value) {
  57039. if (this.particleEmitterType.direction1) {
  57040. this.particleEmitterType.direction1 = value;
  57041. }
  57042. },
  57043. enumerable: true,
  57044. configurable: true
  57045. });
  57046. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57047. /**
  57048. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57049. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57050. */
  57051. get: function () {
  57052. if (this.particleEmitterType.direction2) {
  57053. return this.particleEmitterType.direction2;
  57054. }
  57055. return BABYLON.Vector3.Zero();
  57056. },
  57057. set: function (value) {
  57058. if (this.particleEmitterType.direction2) {
  57059. this.particleEmitterType.direction2 = value;
  57060. }
  57061. },
  57062. enumerable: true,
  57063. configurable: true
  57064. });
  57065. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57066. /**
  57067. * 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.
  57068. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57069. */
  57070. get: function () {
  57071. if (this.particleEmitterType.minEmitBox) {
  57072. return this.particleEmitterType.minEmitBox;
  57073. }
  57074. return BABYLON.Vector3.Zero();
  57075. },
  57076. set: function (value) {
  57077. if (this.particleEmitterType.minEmitBox) {
  57078. this.particleEmitterType.minEmitBox = value;
  57079. }
  57080. },
  57081. enumerable: true,
  57082. configurable: true
  57083. });
  57084. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57085. /**
  57086. * 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.
  57087. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57088. */
  57089. get: function () {
  57090. if (this.particleEmitterType.maxEmitBox) {
  57091. return this.particleEmitterType.maxEmitBox;
  57092. }
  57093. return BABYLON.Vector3.Zero();
  57094. },
  57095. set: function (value) {
  57096. if (this.particleEmitterType.maxEmitBox) {
  57097. this.particleEmitterType.maxEmitBox = value;
  57098. }
  57099. },
  57100. enumerable: true,
  57101. configurable: true
  57102. });
  57103. /**
  57104. * Gets the maximum number of particles active at the same time.
  57105. * @returns The max number of active particles.
  57106. */
  57107. GPUParticleSystem.prototype.getCapacity = function () {
  57108. return this._capacity;
  57109. };
  57110. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57111. /**
  57112. * Gets or set the number of active particles
  57113. */
  57114. get: function () {
  57115. return this._activeCount;
  57116. },
  57117. set: function (value) {
  57118. this._activeCount = Math.min(value, this._capacity);
  57119. },
  57120. enumerable: true,
  57121. configurable: true
  57122. });
  57123. /**
  57124. * Is this system ready to be used/rendered
  57125. * @return true if the system is ready
  57126. */
  57127. GPUParticleSystem.prototype.isReady = function () {
  57128. if (!this._updateEffect) {
  57129. this._recreateUpdateEffect();
  57130. this._recreateRenderEffect();
  57131. return false;
  57132. }
  57133. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57134. return false;
  57135. }
  57136. return true;
  57137. };
  57138. /**
  57139. * Gets Wether the system has been started.
  57140. * @returns True if it has been started, otherwise false.
  57141. */
  57142. GPUParticleSystem.prototype.isStarted = function () {
  57143. return this._started;
  57144. };
  57145. /**
  57146. * Starts the particle system and begins to emit.
  57147. */
  57148. GPUParticleSystem.prototype.start = function () {
  57149. this._started = true;
  57150. this._stopped = false;
  57151. this._preWarmDone = false;
  57152. };
  57153. /**
  57154. * Stops the particle system.
  57155. */
  57156. GPUParticleSystem.prototype.stop = function () {
  57157. this._stopped = true;
  57158. };
  57159. /**
  57160. * Remove all active particles
  57161. */
  57162. GPUParticleSystem.prototype.reset = function () {
  57163. this._releaseBuffers();
  57164. this._releaseVAOs();
  57165. this._currentActiveCount = 0;
  57166. this._targetIndex = 0;
  57167. };
  57168. /**
  57169. * Returns the string "GPUParticleSystem"
  57170. * @returns a string containing the class name
  57171. */
  57172. GPUParticleSystem.prototype.getClassName = function () {
  57173. return "GPUParticleSystem";
  57174. };
  57175. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57176. /**
  57177. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57178. */
  57179. get: function () {
  57180. return this._isBillboardBased;
  57181. },
  57182. set: function (value) {
  57183. if (this._isBillboardBased === value) {
  57184. return;
  57185. }
  57186. this._isBillboardBased = value;
  57187. this._releaseBuffers();
  57188. },
  57189. enumerable: true,
  57190. configurable: true
  57191. });
  57192. /**
  57193. * Gets the current list of color gradients.
  57194. * You must use addColorGradient and removeColorGradient to udpate this list
  57195. * @returns the list of color gradients
  57196. */
  57197. GPUParticleSystem.prototype.getColorGradients = function () {
  57198. return this._colorGradients;
  57199. };
  57200. /**
  57201. * Gets the current list of size gradients.
  57202. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57203. * @returns the list of size gradients
  57204. */
  57205. GPUParticleSystem.prototype.getSizeGradients = function () {
  57206. return this._sizeGradients;
  57207. };
  57208. /**
  57209. * Adds a new color gradient
  57210. * @param gradient defines the gradient to use (between 0 and 1)
  57211. * @param color defines the color to affect to the specified gradient
  57212. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57213. */
  57214. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57215. if (!this._colorGradients) {
  57216. this._colorGradients = [];
  57217. }
  57218. var colorGradient = new BABYLON.ColorGradient();
  57219. colorGradient.gradient = gradient;
  57220. colorGradient.color1 = color1;
  57221. this._colorGradients.push(colorGradient);
  57222. this._colorGradients.sort(function (a, b) {
  57223. if (a.gradient < b.gradient) {
  57224. return -1;
  57225. }
  57226. else if (a.gradient > b.gradient) {
  57227. return 1;
  57228. }
  57229. return 0;
  57230. });
  57231. if (this._colorGradientsTexture) {
  57232. this._colorGradientsTexture.dispose();
  57233. this._colorGradientsTexture = null;
  57234. }
  57235. this._releaseBuffers();
  57236. return this;
  57237. };
  57238. /**
  57239. * Remove a specific color gradient
  57240. * @param gradient defines the gradient to remove
  57241. */
  57242. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57243. if (!this._colorGradients) {
  57244. return this;
  57245. }
  57246. var index = 0;
  57247. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57248. var colorGradient = _a[_i];
  57249. if (colorGradient.gradient === gradient) {
  57250. this._colorGradients.splice(index, 1);
  57251. break;
  57252. }
  57253. index++;
  57254. }
  57255. if (this._colorGradientsTexture) {
  57256. this._colorGradientsTexture.dispose();
  57257. this._colorGradientsTexture = null;
  57258. }
  57259. this._releaseBuffers();
  57260. return this;
  57261. };
  57262. /**
  57263. * Adds a new size gradient
  57264. * @param gradient defines the gradient to use (between 0 and 1)
  57265. * @param factor defines the size factor to affect to the specified gradient
  57266. */
  57267. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57268. if (!this._sizeGradients) {
  57269. this._sizeGradients = [];
  57270. }
  57271. var sizeGradient = new BABYLON.FactorGradient();
  57272. sizeGradient.gradient = gradient;
  57273. sizeGradient.factor = factor;
  57274. this._sizeGradients.push(sizeGradient);
  57275. this._sizeGradients.sort(function (a, b) {
  57276. if (a.gradient < b.gradient) {
  57277. return -1;
  57278. }
  57279. else if (a.gradient > b.gradient) {
  57280. return 1;
  57281. }
  57282. return 0;
  57283. });
  57284. if (this._sizeGradientsTexture) {
  57285. this._sizeGradientsTexture.dispose();
  57286. this._sizeGradientsTexture = null;
  57287. }
  57288. this._releaseBuffers();
  57289. return this;
  57290. };
  57291. /**
  57292. * Remove a specific size gradient
  57293. * @param gradient defines the gradient to remove
  57294. */
  57295. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57296. if (!this._sizeGradients) {
  57297. return this;
  57298. }
  57299. var index = 0;
  57300. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  57301. var sizeGradient = _a[_i];
  57302. if (sizeGradient.gradient === gradient) {
  57303. this._sizeGradients.splice(index, 1);
  57304. break;
  57305. }
  57306. index++;
  57307. }
  57308. if (this._sizeGradientsTexture) {
  57309. this._sizeGradientsTexture.dispose();
  57310. this._sizeGradientsTexture = null;
  57311. }
  57312. this._releaseBuffers();
  57313. return this;
  57314. };
  57315. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57316. var updateVertexBuffers = {};
  57317. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57318. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57319. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57320. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57321. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57322. var offset = 12;
  57323. if (this._sizeGradientsTexture) {
  57324. updateVertexBuffers["initialSize"] = source.createVertexBuffer("initialSize", offset, 3);
  57325. offset += 3;
  57326. }
  57327. if (!this._colorGradientsTexture) {
  57328. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57329. offset += 4;
  57330. }
  57331. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57332. offset += 3;
  57333. if (!this._isBillboardBased) {
  57334. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57335. offset += 3;
  57336. }
  57337. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57338. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57339. this._engine.bindArrayBuffer(null);
  57340. return vao;
  57341. };
  57342. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57343. var renderVertexBuffers = {};
  57344. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57345. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57346. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57347. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57348. var offset = 12;
  57349. if (this._sizeGradientsTexture) {
  57350. offset += 3;
  57351. }
  57352. if (!this._colorGradientsTexture) {
  57353. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57354. offset += 4;
  57355. }
  57356. offset += 3; // Direction
  57357. if (!this._isBillboardBased) {
  57358. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57359. offset += 3;
  57360. }
  57361. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  57362. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57363. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57364. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57365. this._engine.bindArrayBuffer(null);
  57366. return vao;
  57367. };
  57368. GPUParticleSystem.prototype._initialize = function (force) {
  57369. if (force === void 0) { force = false; }
  57370. if (this._buffer0 && !force) {
  57371. return;
  57372. }
  57373. var engine = this._scene.getEngine();
  57374. var data = new Array();
  57375. if (!this.isBillboardBased) {
  57376. this._attributesStrideSize += 3;
  57377. }
  57378. if (this._colorGradientsTexture) {
  57379. this._attributesStrideSize -= 4;
  57380. }
  57381. if (this._sizeGradientsTexture) {
  57382. this._attributesStrideSize += 3;
  57383. }
  57384. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57385. // position
  57386. data.push(0.0);
  57387. data.push(0.0);
  57388. data.push(0.0);
  57389. // Age and life
  57390. data.push(0.0); // create the particle as a dead one to create a new one at start
  57391. data.push(0.0);
  57392. // Seed
  57393. data.push(Math.random());
  57394. data.push(Math.random());
  57395. data.push(Math.random());
  57396. data.push(Math.random());
  57397. // Size
  57398. data.push(0.0);
  57399. data.push(0.0);
  57400. data.push(0.0);
  57401. if (this._sizeGradientsTexture) {
  57402. data.push(0.0);
  57403. data.push(0.0);
  57404. data.push(0.0);
  57405. }
  57406. if (!this._colorGradientsTexture) {
  57407. // color
  57408. data.push(0.0);
  57409. data.push(0.0);
  57410. data.push(0.0);
  57411. data.push(0.0);
  57412. }
  57413. // direction
  57414. data.push(0.0);
  57415. data.push(0.0);
  57416. data.push(0.0);
  57417. if (!this.isBillboardBased) {
  57418. // initialDirection
  57419. data.push(0.0);
  57420. data.push(0.0);
  57421. data.push(0.0);
  57422. }
  57423. // angle
  57424. data.push(0.0);
  57425. data.push(0.0);
  57426. }
  57427. // Sprite data
  57428. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57429. -0.5, 0.5, 0, 1,
  57430. -0.5, -0.5, 0, 0,
  57431. 0.5, -0.5, 1, 0]);
  57432. // Buffers
  57433. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57434. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57435. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57436. // Update VAO
  57437. this._updateVAO = [];
  57438. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57439. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57440. // Render VAO
  57441. this._renderVAO = [];
  57442. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57443. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57444. // Links
  57445. this._sourceBuffer = this._buffer0;
  57446. this._targetBuffer = this._buffer1;
  57447. };
  57448. /** @hidden */
  57449. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57450. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57451. if (this._isBillboardBased) {
  57452. defines += "\n#define BILLBOARD";
  57453. }
  57454. if (this._colorGradientsTexture) {
  57455. defines += "\n#define COLORGRADIENTS";
  57456. }
  57457. if (this._sizeGradientsTexture) {
  57458. defines += "\n#define SIZEGRADIENTS";
  57459. }
  57460. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57461. return;
  57462. }
  57463. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57464. if (this._sizeGradientsTexture) {
  57465. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialSize");
  57466. }
  57467. if (!this._colorGradientsTexture) {
  57468. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57469. }
  57470. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57471. if (!this._isBillboardBased) {
  57472. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57473. }
  57474. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57475. this._updateEffectOptions.defines = defines;
  57476. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57477. };
  57478. /** @hidden */
  57479. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57480. var defines = "";
  57481. if (this._scene.clipPlane) {
  57482. defines = "\n#define CLIPPLANE";
  57483. }
  57484. if (this._isBillboardBased) {
  57485. defines += "\n#define BILLBOARD";
  57486. }
  57487. if (this._colorGradientsTexture) {
  57488. defines += "\n#define COLORGRADIENTS";
  57489. }
  57490. if (this._renderEffect && this._renderEffect.defines === defines) {
  57491. return;
  57492. }
  57493. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57494. };
  57495. /**
  57496. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57497. * @param preWarm defines if we are in the pre-warmimg phase
  57498. */
  57499. GPUParticleSystem.prototype.animate = function (preWarm) {
  57500. if (preWarm === void 0) { preWarm = false; }
  57501. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57502. this._actualFrame += this._timeDelta;
  57503. if (!this._stopped) {
  57504. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57505. this.stop();
  57506. }
  57507. }
  57508. };
  57509. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57510. if (!this._sizeGradients || !this._sizeGradients.length || this._sizeGradientsTexture) {
  57511. return;
  57512. }
  57513. var textureWidth = 256;
  57514. var data = new Float32Array(textureWidth);
  57515. for (var x = 0; x < textureWidth; x++) {
  57516. var ratio = x / textureWidth;
  57517. BABYLON.Tools.GetCurrentGradient(ratio, this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57518. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  57519. });
  57520. }
  57521. this._sizeGradientsTexture = BABYLON.RawTexture.CreateRTexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57522. };
  57523. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57524. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57525. return;
  57526. }
  57527. var textureWidth = 256;
  57528. var data = new Uint8Array(textureWidth * 4);
  57529. var tmpColor = BABYLON.Tmp.Color4[0];
  57530. for (var x = 0; x < textureWidth; x++) {
  57531. var ratio = x / textureWidth;
  57532. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57533. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57534. data[x * 4] = tmpColor.r * 255;
  57535. data[x * 4 + 1] = tmpColor.g * 255;
  57536. data[x * 4 + 2] = tmpColor.b * 255;
  57537. data[x * 4 + 3] = tmpColor.a * 255;
  57538. });
  57539. }
  57540. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57541. };
  57542. /**
  57543. * Renders the particle system in its current state
  57544. * @param preWarm defines if the system should only update the particles but not render them
  57545. * @returns the current number of particles
  57546. */
  57547. GPUParticleSystem.prototype.render = function (preWarm) {
  57548. if (preWarm === void 0) { preWarm = false; }
  57549. if (!this._started) {
  57550. return 0;
  57551. }
  57552. this._createColorGradientTexture();
  57553. this._createSizeGradientTexture();
  57554. this._recreateUpdateEffect();
  57555. this._recreateRenderEffect();
  57556. if (!this.isReady()) {
  57557. return 0;
  57558. }
  57559. if (!preWarm) {
  57560. if (!this._preWarmDone && this.preWarmCycles) {
  57561. for (var index = 0; index < this.preWarmCycles; index++) {
  57562. this.animate(true);
  57563. this.render(true);
  57564. }
  57565. this._preWarmDone = true;
  57566. }
  57567. if (this._currentRenderId === this._scene.getRenderId()) {
  57568. return 0;
  57569. }
  57570. this._currentRenderId = this._scene.getRenderId();
  57571. }
  57572. // Get everything ready to render
  57573. this._initialize();
  57574. this._accumulatedCount += this.emitRate * this._timeDelta;
  57575. if (this._accumulatedCount > 1) {
  57576. var intPart = this._accumulatedCount | 0;
  57577. this._accumulatedCount -= intPart;
  57578. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57579. }
  57580. if (!this._currentActiveCount) {
  57581. return 0;
  57582. }
  57583. // Enable update effect
  57584. this._engine.enableEffect(this._updateEffect);
  57585. this._engine.setState(false);
  57586. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57587. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57588. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57589. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57590. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57591. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57592. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57593. if (!this._colorGradientsTexture) {
  57594. this._updateEffect.setDirectColor4("color1", this.color1);
  57595. this._updateEffect.setDirectColor4("color2", this.color2);
  57596. }
  57597. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57598. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57599. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57600. this._updateEffect.setVector3("gravity", this.gravity);
  57601. if (this._sizeGradientsTexture) {
  57602. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57603. }
  57604. if (this.particleEmitterType) {
  57605. this.particleEmitterType.applyToShader(this._updateEffect);
  57606. }
  57607. var emitterWM;
  57608. if (this.emitter.position) {
  57609. var emitterMesh = this.emitter;
  57610. emitterWM = emitterMesh.getWorldMatrix();
  57611. }
  57612. else {
  57613. var emitterPosition = this.emitter;
  57614. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57615. }
  57616. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57617. // Bind source VAO
  57618. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57619. // Update
  57620. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57621. this._engine.setRasterizerState(false);
  57622. this._engine.beginTransformFeedback();
  57623. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57624. this._engine.endTransformFeedback();
  57625. this._engine.setRasterizerState(true);
  57626. this._engine.bindTransformFeedbackBuffer(null);
  57627. if (!preWarm) {
  57628. // Enable render effect
  57629. this._engine.enableEffect(this._renderEffect);
  57630. var viewMatrix = this._scene.getViewMatrix();
  57631. this._renderEffect.setMatrix("view", viewMatrix);
  57632. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57633. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57634. if (this._colorGradientsTexture) {
  57635. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57636. }
  57637. else {
  57638. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57639. }
  57640. if (this._scene.clipPlane) {
  57641. var clipPlane = this._scene.clipPlane;
  57642. var invView = viewMatrix.clone();
  57643. invView.invert();
  57644. this._renderEffect.setMatrix("invView", invView);
  57645. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57646. }
  57647. // Draw order
  57648. switch (this.blendMode) {
  57649. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57650. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57651. break;
  57652. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57653. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57654. break;
  57655. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57656. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57657. break;
  57658. }
  57659. if (this.forceDepthWrite) {
  57660. this._engine.setDepthWrite(true);
  57661. }
  57662. // Bind source VAO
  57663. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57664. // Render
  57665. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57666. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57667. }
  57668. // Switch VAOs
  57669. this._targetIndex++;
  57670. if (this._targetIndex === 2) {
  57671. this._targetIndex = 0;
  57672. }
  57673. // Switch buffers
  57674. var tmpBuffer = this._sourceBuffer;
  57675. this._sourceBuffer = this._targetBuffer;
  57676. this._targetBuffer = tmpBuffer;
  57677. return this._currentActiveCount;
  57678. };
  57679. /**
  57680. * Rebuilds the particle system
  57681. */
  57682. GPUParticleSystem.prototype.rebuild = function () {
  57683. this._initialize(true);
  57684. };
  57685. GPUParticleSystem.prototype._releaseBuffers = function () {
  57686. if (this._buffer0) {
  57687. this._buffer0.dispose();
  57688. this._buffer0 = null;
  57689. }
  57690. if (this._buffer1) {
  57691. this._buffer1.dispose();
  57692. this._buffer1 = null;
  57693. }
  57694. if (this._spriteBuffer) {
  57695. this._spriteBuffer.dispose();
  57696. this._spriteBuffer = null;
  57697. }
  57698. };
  57699. GPUParticleSystem.prototype._releaseVAOs = function () {
  57700. if (!this._updateVAO) {
  57701. return;
  57702. }
  57703. for (var index = 0; index < this._updateVAO.length; index++) {
  57704. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57705. }
  57706. this._updateVAO = [];
  57707. for (var index = 0; index < this._renderVAO.length; index++) {
  57708. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57709. }
  57710. this._renderVAO = [];
  57711. };
  57712. /**
  57713. * Disposes the particle system and free the associated resources
  57714. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57715. */
  57716. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57717. if (disposeTexture === void 0) { disposeTexture = true; }
  57718. var index = this._scene.particleSystems.indexOf(this);
  57719. if (index > -1) {
  57720. this._scene.particleSystems.splice(index, 1);
  57721. }
  57722. this._releaseBuffers();
  57723. this._releaseVAOs();
  57724. if (this._colorGradientsTexture) {
  57725. this._colorGradientsTexture.dispose();
  57726. this._colorGradientsTexture = null;
  57727. }
  57728. if (this._sizeGradientsTexture) {
  57729. this._sizeGradientsTexture.dispose();
  57730. this._sizeGradientsTexture = null;
  57731. }
  57732. if (this._randomTexture) {
  57733. this._randomTexture.dispose();
  57734. this._randomTexture = null;
  57735. }
  57736. if (this._randomTexture2) {
  57737. this._randomTexture2.dispose();
  57738. this._randomTexture2 = null;
  57739. }
  57740. if (disposeTexture && this.particleTexture) {
  57741. this.particleTexture.dispose();
  57742. this.particleTexture = null;
  57743. }
  57744. // Callback
  57745. this.onDisposeObservable.notifyObservers(this);
  57746. this.onDisposeObservable.clear();
  57747. };
  57748. /**
  57749. * Clones the particle system.
  57750. * @param name The name of the cloned object
  57751. * @param newEmitter The new emitter to use
  57752. * @returns the cloned particle system
  57753. */
  57754. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57755. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57756. BABYLON.Tools.DeepCopy(this, result);
  57757. if (newEmitter === undefined) {
  57758. newEmitter = this.emitter;
  57759. }
  57760. result.emitter = newEmitter;
  57761. if (this.particleTexture) {
  57762. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57763. }
  57764. return result;
  57765. };
  57766. /**
  57767. * Serializes the particle system to a JSON object.
  57768. * @returns the JSON object
  57769. */
  57770. GPUParticleSystem.prototype.serialize = function () {
  57771. var serializationObject = {};
  57772. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  57773. return serializationObject;
  57774. };
  57775. /**
  57776. * Parses a JSON object to create a GPU particle system.
  57777. * @param parsedParticleSystem The JSON object to parse
  57778. * @param scene The scene to create the particle system in
  57779. * @param rootUrl The root url to use to load external dependencies like texture
  57780. * @returns the parsed GPU particle system
  57781. */
  57782. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57783. var name = parsedParticleSystem.name;
  57784. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57785. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57786. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57787. return particleSystem;
  57788. };
  57789. return GPUParticleSystem;
  57790. }());
  57791. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57792. })(BABYLON || (BABYLON = {}));
  57793. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57794. var BABYLON;
  57795. (function (BABYLON) {
  57796. /**
  57797. * Represents one particle of a solid particle system.
  57798. */
  57799. var SolidParticle = /** @class */ (function () {
  57800. /**
  57801. * Creates a Solid Particle object.
  57802. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57803. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57804. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57805. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57806. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57807. * @param shapeId (integer) is the model shape identifier in the SPS.
  57808. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57809. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57810. */
  57811. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57812. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57813. /**
  57814. * particle global index
  57815. */
  57816. this.idx = 0;
  57817. /**
  57818. * The color of the particle
  57819. */
  57820. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57821. /**
  57822. * The world space position of the particle.
  57823. */
  57824. this.position = BABYLON.Vector3.Zero();
  57825. /**
  57826. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57827. */
  57828. this.rotation = BABYLON.Vector3.Zero();
  57829. /**
  57830. * The scaling of the particle.
  57831. */
  57832. this.scaling = BABYLON.Vector3.One();
  57833. /**
  57834. * The uvs of the particle.
  57835. */
  57836. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57837. /**
  57838. * The current speed of the particle.
  57839. */
  57840. this.velocity = BABYLON.Vector3.Zero();
  57841. /**
  57842. * The pivot point in the particle local space.
  57843. */
  57844. this.pivot = BABYLON.Vector3.Zero();
  57845. /**
  57846. * Must the particle be translated from its pivot point in its local space ?
  57847. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57848. * Default : false
  57849. */
  57850. this.translateFromPivot = false;
  57851. /**
  57852. * Is the particle active or not ?
  57853. */
  57854. this.alive = true;
  57855. /**
  57856. * Is the particle visible or not ?
  57857. */
  57858. this.isVisible = true;
  57859. /**
  57860. * Index of this particle in the global "positions" array (Internal use)
  57861. */
  57862. this._pos = 0;
  57863. /**
  57864. * Index of this particle in the global "indices" array (Internal use)
  57865. */
  57866. this._ind = 0;
  57867. /**
  57868. * ModelShape id of this particle
  57869. */
  57870. this.shapeId = 0;
  57871. /**
  57872. * Index of the particle in its shape id (Internal use)
  57873. */
  57874. this.idxInShape = 0;
  57875. /**
  57876. * Still set as invisible in order to skip useless computations (Internal use)
  57877. */
  57878. this._stillInvisible = false;
  57879. /**
  57880. * Last computed particle rotation matrix
  57881. */
  57882. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57883. /**
  57884. * Parent particle Id, if any.
  57885. * Default null.
  57886. */
  57887. this.parentId = null;
  57888. /**
  57889. * Internal global position in the SPS.
  57890. */
  57891. this._globalPosition = BABYLON.Vector3.Zero();
  57892. this.idx = particleIndex;
  57893. this._pos = positionIndex;
  57894. this._ind = indiceIndex;
  57895. this._model = model;
  57896. this.shapeId = shapeId;
  57897. this.idxInShape = idxInShape;
  57898. this._sps = sps;
  57899. if (modelBoundingInfo) {
  57900. this._modelBoundingInfo = modelBoundingInfo;
  57901. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57902. }
  57903. }
  57904. Object.defineProperty(SolidParticle.prototype, "scale", {
  57905. /**
  57906. * Legacy support, changed scale to scaling
  57907. */
  57908. get: function () {
  57909. return this.scaling;
  57910. },
  57911. /**
  57912. * Legacy support, changed scale to scaling
  57913. */
  57914. set: function (scale) {
  57915. this.scaling = scale;
  57916. },
  57917. enumerable: true,
  57918. configurable: true
  57919. });
  57920. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57921. /**
  57922. * Legacy support, changed quaternion to rotationQuaternion
  57923. */
  57924. get: function () {
  57925. return this.rotationQuaternion;
  57926. },
  57927. /**
  57928. * Legacy support, changed quaternion to rotationQuaternion
  57929. */
  57930. set: function (q) {
  57931. this.rotationQuaternion = q;
  57932. },
  57933. enumerable: true,
  57934. configurable: true
  57935. });
  57936. /**
  57937. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57938. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57939. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57940. * @returns true if it intersects
  57941. */
  57942. SolidParticle.prototype.intersectsMesh = function (target) {
  57943. if (!this._boundingInfo || !target._boundingInfo) {
  57944. return false;
  57945. }
  57946. if (this._sps._bSphereOnly) {
  57947. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57948. }
  57949. return this._boundingInfo.intersects(target._boundingInfo, false);
  57950. };
  57951. return SolidParticle;
  57952. }());
  57953. BABYLON.SolidParticle = SolidParticle;
  57954. /**
  57955. * Represents the shape of the model used by one particle of a solid particle system.
  57956. * SPS internal tool, don't use it manually.
  57957. */
  57958. var ModelShape = /** @class */ (function () {
  57959. /**
  57960. * 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.
  57961. * SPS internal tool, don't use it manually.
  57962. * @hidden
  57963. */
  57964. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57965. /**
  57966. * length of the shape in the model indices array (internal use)
  57967. */
  57968. this._indicesLength = 0;
  57969. this.shapeID = id;
  57970. this._shape = shape;
  57971. this._indicesLength = indicesLength;
  57972. this._shapeUV = shapeUV;
  57973. this._positionFunction = posFunction;
  57974. this._vertexFunction = vtxFunction;
  57975. }
  57976. return ModelShape;
  57977. }());
  57978. BABYLON.ModelShape = ModelShape;
  57979. /**
  57980. * Represents a Depth Sorted Particle in the solid particle system.
  57981. */
  57982. var DepthSortedParticle = /** @class */ (function () {
  57983. function DepthSortedParticle() {
  57984. /**
  57985. * Index of the particle in the "indices" array
  57986. */
  57987. this.ind = 0;
  57988. /**
  57989. * Length of the particle shape in the "indices" array
  57990. */
  57991. this.indicesLength = 0;
  57992. /**
  57993. * Squared distance from the particle to the camera
  57994. */
  57995. this.sqDistance = 0.0;
  57996. }
  57997. return DepthSortedParticle;
  57998. }());
  57999. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58000. })(BABYLON || (BABYLON = {}));
  58001. //# sourceMappingURL=babylon.solidParticle.js.map
  58002. var BABYLON;
  58003. (function (BABYLON) {
  58004. /**
  58005. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58006. *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.
  58007. * The SPS is also a particle system. It provides some methods to manage the particles.
  58008. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58009. *
  58010. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58011. */
  58012. var SolidParticleSystem = /** @class */ (function () {
  58013. /**
  58014. * Creates a SPS (Solid Particle System) object.
  58015. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58016. * @param scene (Scene) is the scene in which the SPS is added.
  58017. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58018. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58019. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58020. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58021. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58022. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58023. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58024. */
  58025. function SolidParticleSystem(name, scene, options) {
  58026. /**
  58027. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58028. * Example : var p = SPS.particles[i];
  58029. */
  58030. this.particles = new Array();
  58031. /**
  58032. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58033. */
  58034. this.nbParticles = 0;
  58035. /**
  58036. * If the particles must ever face the camera (default false). Useful for planar particles.
  58037. */
  58038. this.billboard = false;
  58039. /**
  58040. * Recompute normals when adding a shape
  58041. */
  58042. this.recomputeNormals = true;
  58043. /**
  58044. * This a counter ofr your own usage. It's not set by any SPS functions.
  58045. */
  58046. this.counter = 0;
  58047. /**
  58048. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58049. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58050. */
  58051. this.vars = {};
  58052. /**
  58053. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58054. */
  58055. this._bSphereOnly = false;
  58056. /**
  58057. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58058. */
  58059. this._bSphereRadiusFactor = 1.0;
  58060. this._positions = new Array();
  58061. this._indices = new Array();
  58062. this._normals = new Array();
  58063. this._colors = new Array();
  58064. this._uvs = new Array();
  58065. this._index = 0; // indices index
  58066. this._updatable = true;
  58067. this._pickable = false;
  58068. this._isVisibilityBoxLocked = false;
  58069. this._alwaysVisible = false;
  58070. this._depthSort = false;
  58071. this._shapeCounter = 0;
  58072. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58073. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58074. this._computeParticleColor = true;
  58075. this._computeParticleTexture = true;
  58076. this._computeParticleRotation = true;
  58077. this._computeParticleVertex = false;
  58078. this._computeBoundingBox = false;
  58079. this._depthSortParticles = true;
  58080. this._cam_axisZ = BABYLON.Vector3.Zero();
  58081. this._cam_axisY = BABYLON.Vector3.Zero();
  58082. this._cam_axisX = BABYLON.Vector3.Zero();
  58083. this._axisZ = BABYLON.Axis.Z;
  58084. this._camDir = BABYLON.Vector3.Zero();
  58085. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58086. this._rotMatrix = new BABYLON.Matrix();
  58087. this._invertMatrix = new BABYLON.Matrix();
  58088. this._rotated = BABYLON.Vector3.Zero();
  58089. this._quaternion = new BABYLON.Quaternion();
  58090. this._vertex = BABYLON.Vector3.Zero();
  58091. this._normal = BABYLON.Vector3.Zero();
  58092. this._yaw = 0.0;
  58093. this._pitch = 0.0;
  58094. this._roll = 0.0;
  58095. this._halfroll = 0.0;
  58096. this._halfpitch = 0.0;
  58097. this._halfyaw = 0.0;
  58098. this._sinRoll = 0.0;
  58099. this._cosRoll = 0.0;
  58100. this._sinPitch = 0.0;
  58101. this._cosPitch = 0.0;
  58102. this._sinYaw = 0.0;
  58103. this._cosYaw = 0.0;
  58104. this._mustUnrotateFixedNormals = false;
  58105. this._minimum = BABYLON.Vector3.Zero();
  58106. this._maximum = BABYLON.Vector3.Zero();
  58107. this._minBbox = BABYLON.Vector3.Zero();
  58108. this._maxBbox = BABYLON.Vector3.Zero();
  58109. this._particlesIntersect = false;
  58110. this._depthSortFunction = function (p1, p2) {
  58111. return (p2.sqDistance - p1.sqDistance);
  58112. };
  58113. this._needs32Bits = false;
  58114. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58115. this._scaledPivot = BABYLON.Vector3.Zero();
  58116. this._particleHasParent = false;
  58117. this.name = name;
  58118. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58119. this._camera = scene.activeCamera;
  58120. this._pickable = options ? options.isPickable : false;
  58121. this._depthSort = options ? options.enableDepthSort : false;
  58122. this._particlesIntersect = options ? options.particleIntersection : false;
  58123. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58124. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58125. if (options && options.updatable !== undefined) {
  58126. this._updatable = options.updatable;
  58127. }
  58128. else {
  58129. this._updatable = true;
  58130. }
  58131. if (this._pickable) {
  58132. this.pickedParticles = [];
  58133. }
  58134. if (this._depthSort) {
  58135. this.depthSortedParticles = [];
  58136. }
  58137. }
  58138. /**
  58139. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58140. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58141. * @returns the created mesh
  58142. */
  58143. SolidParticleSystem.prototype.buildMesh = function () {
  58144. if (this.nbParticles === 0) {
  58145. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58146. this.addShape(triangle, 1);
  58147. triangle.dispose();
  58148. }
  58149. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58150. this._positions32 = new Float32Array(this._positions);
  58151. this._uvs32 = new Float32Array(this._uvs);
  58152. this._colors32 = new Float32Array(this._colors);
  58153. if (this.recomputeNormals) {
  58154. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58155. }
  58156. this._normals32 = new Float32Array(this._normals);
  58157. this._fixedNormal32 = new Float32Array(this._normals);
  58158. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58159. this._unrotateFixedNormals();
  58160. }
  58161. var vertexData = new BABYLON.VertexData();
  58162. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58163. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58164. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58165. if (this._uvs32.length > 0) {
  58166. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58167. }
  58168. if (this._colors32.length > 0) {
  58169. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58170. }
  58171. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58172. vertexData.applyToMesh(mesh, this._updatable);
  58173. this.mesh = mesh;
  58174. this.mesh.isPickable = this._pickable;
  58175. // free memory
  58176. if (!this._depthSort) {
  58177. this._indices = null;
  58178. }
  58179. this._positions = null;
  58180. this._normals = null;
  58181. this._uvs = null;
  58182. this._colors = null;
  58183. if (!this._updatable) {
  58184. this.particles.length = 0;
  58185. }
  58186. return mesh;
  58187. };
  58188. /**
  58189. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58190. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58191. * Thus the particles generated from `digest()` have their property `position` set yet.
  58192. * @param mesh ( Mesh ) is the mesh to be digested
  58193. * @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
  58194. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58195. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58196. * @returns the current SPS
  58197. */
  58198. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58199. var size = (options && options.facetNb) || 1;
  58200. var number = (options && options.number) || 0;
  58201. var delta = (options && options.delta) || 0;
  58202. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58203. var meshInd = mesh.getIndices();
  58204. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58205. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58206. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58207. var f = 0; // facet counter
  58208. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58209. // compute size from number
  58210. if (number) {
  58211. number = (number > totalFacets) ? totalFacets : number;
  58212. size = Math.round(totalFacets / number);
  58213. delta = 0;
  58214. }
  58215. else {
  58216. size = (size > totalFacets) ? totalFacets : size;
  58217. }
  58218. var facetPos = []; // submesh positions
  58219. var facetInd = []; // submesh indices
  58220. var facetUV = []; // submesh UV
  58221. var facetCol = []; // submesh colors
  58222. var barycenter = BABYLON.Vector3.Zero();
  58223. var sizeO = size;
  58224. while (f < totalFacets) {
  58225. size = sizeO + Math.floor((1 + delta) * Math.random());
  58226. if (f > totalFacets - size) {
  58227. size = totalFacets - f;
  58228. }
  58229. // reset temp arrays
  58230. facetPos.length = 0;
  58231. facetInd.length = 0;
  58232. facetUV.length = 0;
  58233. facetCol.length = 0;
  58234. // iterate over "size" facets
  58235. var fi = 0;
  58236. for (var j = f * 3; j < (f + size) * 3; j++) {
  58237. facetInd.push(fi);
  58238. var i = meshInd[j];
  58239. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58240. if (meshUV) {
  58241. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58242. }
  58243. if (meshCol) {
  58244. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58245. }
  58246. fi++;
  58247. }
  58248. // create a model shape for each single particle
  58249. var idx = this.nbParticles;
  58250. var shape = this._posToShape(facetPos);
  58251. var shapeUV = this._uvsToShapeUV(facetUV);
  58252. // compute the barycenter of the shape
  58253. var v;
  58254. for (v = 0; v < shape.length; v++) {
  58255. barycenter.addInPlace(shape[v]);
  58256. }
  58257. barycenter.scaleInPlace(1 / shape.length);
  58258. // shift the shape from its barycenter to the origin
  58259. for (v = 0; v < shape.length; v++) {
  58260. shape[v].subtractInPlace(barycenter);
  58261. }
  58262. var bInfo;
  58263. if (this._particlesIntersect) {
  58264. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58265. }
  58266. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58267. // add the particle in the SPS
  58268. var currentPos = this._positions.length;
  58269. var currentInd = this._indices.length;
  58270. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58271. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58272. // initialize the particle position
  58273. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58274. this._index += shape.length;
  58275. idx++;
  58276. this.nbParticles++;
  58277. this._shapeCounter++;
  58278. f += size;
  58279. }
  58280. return this;
  58281. };
  58282. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58283. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58284. var index = 0;
  58285. var idx = 0;
  58286. for (var p = 0; p < this.particles.length; p++) {
  58287. this._particle = this.particles[p];
  58288. this._shape = this._particle._model._shape;
  58289. if (this._particle.rotationQuaternion) {
  58290. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58291. }
  58292. else {
  58293. this._yaw = this._particle.rotation.y;
  58294. this._pitch = this._particle.rotation.x;
  58295. this._roll = this._particle.rotation.z;
  58296. this._quaternionRotationYPR();
  58297. }
  58298. this._quaternionToRotationMatrix();
  58299. this._rotMatrix.invertToRef(this._invertMatrix);
  58300. for (var pt = 0; pt < this._shape.length; pt++) {
  58301. idx = index + pt * 3;
  58302. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58303. this._fixedNormal32[idx] = this._normal.x;
  58304. this._fixedNormal32[idx + 1] = this._normal.y;
  58305. this._fixedNormal32[idx + 2] = this._normal.z;
  58306. }
  58307. index = idx + 3;
  58308. }
  58309. };
  58310. //reset copy
  58311. SolidParticleSystem.prototype._resetCopy = function () {
  58312. this._copy.position.x = 0;
  58313. this._copy.position.y = 0;
  58314. this._copy.position.z = 0;
  58315. this._copy.rotation.x = 0;
  58316. this._copy.rotation.y = 0;
  58317. this._copy.rotation.z = 0;
  58318. this._copy.rotationQuaternion = null;
  58319. this._copy.scaling.x = 1.0;
  58320. this._copy.scaling.y = 1.0;
  58321. this._copy.scaling.z = 1.0;
  58322. this._copy.uvs.x = 0;
  58323. this._copy.uvs.y = 0;
  58324. this._copy.uvs.z = 1.0;
  58325. this._copy.uvs.w = 1.0;
  58326. this._copy.color = null;
  58327. this._copy.translateFromPivot = false;
  58328. };
  58329. // _meshBuilder : inserts the shape model in the global SPS mesh
  58330. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58331. var i;
  58332. var u = 0;
  58333. var c = 0;
  58334. var n = 0;
  58335. this._resetCopy();
  58336. if (options && options.positionFunction) { // call to custom positionFunction
  58337. options.positionFunction(this._copy, idx, idxInShape);
  58338. this._mustUnrotateFixedNormals = true;
  58339. }
  58340. if (this._copy.rotationQuaternion) {
  58341. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58342. }
  58343. else {
  58344. this._yaw = this._copy.rotation.y;
  58345. this._pitch = this._copy.rotation.x;
  58346. this._roll = this._copy.rotation.z;
  58347. this._quaternionRotationYPR();
  58348. }
  58349. this._quaternionToRotationMatrix();
  58350. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58351. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58352. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58353. if (this._copy.translateFromPivot) {
  58354. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58355. }
  58356. else {
  58357. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58358. }
  58359. for (i = 0; i < shape.length; i++) {
  58360. this._vertex.x = shape[i].x;
  58361. this._vertex.y = shape[i].y;
  58362. this._vertex.z = shape[i].z;
  58363. if (options && options.vertexFunction) {
  58364. options.vertexFunction(this._copy, this._vertex, i);
  58365. }
  58366. this._vertex.x *= this._copy.scaling.x;
  58367. this._vertex.y *= this._copy.scaling.y;
  58368. this._vertex.z *= this._copy.scaling.z;
  58369. this._vertex.x -= this._scaledPivot.x;
  58370. this._vertex.y -= this._scaledPivot.y;
  58371. this._vertex.z -= this._scaledPivot.z;
  58372. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58373. this._rotated.addInPlace(this._pivotBackTranslation);
  58374. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58375. if (meshUV) {
  58376. 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);
  58377. u += 2;
  58378. }
  58379. if (this._copy.color) {
  58380. this._color = this._copy.color;
  58381. }
  58382. else if (meshCol && meshCol[c] !== undefined) {
  58383. this._color.r = meshCol[c];
  58384. this._color.g = meshCol[c + 1];
  58385. this._color.b = meshCol[c + 2];
  58386. this._color.a = meshCol[c + 3];
  58387. }
  58388. else {
  58389. this._color.r = 1.0;
  58390. this._color.g = 1.0;
  58391. this._color.b = 1.0;
  58392. this._color.a = 1.0;
  58393. }
  58394. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58395. c += 4;
  58396. if (!this.recomputeNormals && meshNor) {
  58397. this._normal.x = meshNor[n];
  58398. this._normal.y = meshNor[n + 1];
  58399. this._normal.z = meshNor[n + 2];
  58400. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58401. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58402. n += 3;
  58403. }
  58404. }
  58405. for (i = 0; i < meshInd.length; i++) {
  58406. var current_ind = p + meshInd[i];
  58407. indices.push(current_ind);
  58408. if (current_ind > 65535) {
  58409. this._needs32Bits = true;
  58410. }
  58411. }
  58412. if (this._pickable) {
  58413. var nbfaces = meshInd.length / 3;
  58414. for (i = 0; i < nbfaces; i++) {
  58415. this.pickedParticles.push({ idx: idx, faceId: i });
  58416. }
  58417. }
  58418. if (this._depthSort) {
  58419. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58420. }
  58421. return this._copy;
  58422. };
  58423. // returns a shape array from positions array
  58424. SolidParticleSystem.prototype._posToShape = function (positions) {
  58425. var shape = [];
  58426. for (var i = 0; i < positions.length; i += 3) {
  58427. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58428. }
  58429. return shape;
  58430. };
  58431. // returns a shapeUV array from a Vector4 uvs
  58432. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58433. var shapeUV = [];
  58434. if (uvs) {
  58435. for (var i = 0; i < uvs.length; i++)
  58436. shapeUV.push(uvs[i]);
  58437. }
  58438. return shapeUV;
  58439. };
  58440. // adds a new particle object in the particles array
  58441. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58442. if (bInfo === void 0) { bInfo = null; }
  58443. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58444. this.particles.push(sp);
  58445. return sp;
  58446. };
  58447. /**
  58448. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58449. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58450. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58451. * @param nb (positive integer) the number of particles to be created from this model
  58452. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58453. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58454. * @returns the number of shapes in the system
  58455. */
  58456. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58457. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58458. var meshInd = mesh.getIndices();
  58459. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58460. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58461. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58462. var bbInfo;
  58463. if (this._particlesIntersect) {
  58464. bbInfo = mesh.getBoundingInfo();
  58465. }
  58466. var shape = this._posToShape(meshPos);
  58467. var shapeUV = this._uvsToShapeUV(meshUV);
  58468. var posfunc = options ? options.positionFunction : null;
  58469. var vtxfunc = options ? options.vertexFunction : null;
  58470. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58471. // particles
  58472. var sp;
  58473. var currentCopy;
  58474. var idx = this.nbParticles;
  58475. for (var i = 0; i < nb; i++) {
  58476. var currentPos = this._positions.length;
  58477. var currentInd = this._indices.length;
  58478. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58479. if (this._updatable) {
  58480. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58481. sp.position.copyFrom(currentCopy.position);
  58482. sp.rotation.copyFrom(currentCopy.rotation);
  58483. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58484. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58485. }
  58486. if (currentCopy.color && sp.color) {
  58487. sp.color.copyFrom(currentCopy.color);
  58488. }
  58489. sp.scaling.copyFrom(currentCopy.scaling);
  58490. sp.uvs.copyFrom(currentCopy.uvs);
  58491. }
  58492. this._index += shape.length;
  58493. idx++;
  58494. }
  58495. this.nbParticles += nb;
  58496. this._shapeCounter++;
  58497. return this._shapeCounter - 1;
  58498. };
  58499. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58500. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58501. this._resetCopy();
  58502. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58503. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58504. }
  58505. if (this._copy.rotationQuaternion) {
  58506. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58507. }
  58508. else {
  58509. this._yaw = this._copy.rotation.y;
  58510. this._pitch = this._copy.rotation.x;
  58511. this._roll = this._copy.rotation.z;
  58512. this._quaternionRotationYPR();
  58513. }
  58514. this._quaternionToRotationMatrix();
  58515. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58516. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58517. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58518. if (this._copy.translateFromPivot) {
  58519. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58520. }
  58521. else {
  58522. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58523. }
  58524. this._shape = particle._model._shape;
  58525. for (var pt = 0; pt < this._shape.length; pt++) {
  58526. this._vertex.x = this._shape[pt].x;
  58527. this._vertex.y = this._shape[pt].y;
  58528. this._vertex.z = this._shape[pt].z;
  58529. if (particle._model._vertexFunction) {
  58530. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58531. }
  58532. this._vertex.x *= this._copy.scaling.x;
  58533. this._vertex.y *= this._copy.scaling.y;
  58534. this._vertex.z *= this._copy.scaling.z;
  58535. this._vertex.x -= this._scaledPivot.x;
  58536. this._vertex.y -= this._scaledPivot.y;
  58537. this._vertex.z -= this._scaledPivot.z;
  58538. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58539. this._rotated.addInPlace(this._pivotBackTranslation);
  58540. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58541. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58542. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58543. }
  58544. particle.position.x = 0.0;
  58545. particle.position.y = 0.0;
  58546. particle.position.z = 0.0;
  58547. particle.rotation.x = 0.0;
  58548. particle.rotation.y = 0.0;
  58549. particle.rotation.z = 0.0;
  58550. particle.rotationQuaternion = null;
  58551. particle.scaling.x = 1.0;
  58552. particle.scaling.y = 1.0;
  58553. particle.scaling.z = 1.0;
  58554. particle.uvs.x = 0.0;
  58555. particle.uvs.y = 0.0;
  58556. particle.uvs.z = 1.0;
  58557. particle.uvs.w = 1.0;
  58558. particle.pivot.x = 0.0;
  58559. particle.pivot.y = 0.0;
  58560. particle.pivot.z = 0.0;
  58561. particle.translateFromPivot = false;
  58562. particle.parentId = null;
  58563. };
  58564. /**
  58565. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58566. * @returns the SPS.
  58567. */
  58568. SolidParticleSystem.prototype.rebuildMesh = function () {
  58569. for (var p = 0; p < this.particles.length; p++) {
  58570. this._rebuildParticle(this.particles[p]);
  58571. }
  58572. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58573. return this;
  58574. };
  58575. /**
  58576. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58577. * This method calls `updateParticle()` for each particle of the SPS.
  58578. * For an animated SPS, it is usually called within the render loop.
  58579. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58580. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58581. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58582. * @returns the SPS.
  58583. */
  58584. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58585. if (start === void 0) { start = 0; }
  58586. if (end === void 0) { end = this.nbParticles - 1; }
  58587. if (update === void 0) { update = true; }
  58588. if (!this._updatable) {
  58589. return this;
  58590. }
  58591. // custom beforeUpdate
  58592. this.beforeUpdateParticles(start, end, update);
  58593. this._cam_axisX.x = 1.0;
  58594. this._cam_axisX.y = 0.0;
  58595. this._cam_axisX.z = 0.0;
  58596. this._cam_axisY.x = 0.0;
  58597. this._cam_axisY.y = 1.0;
  58598. this._cam_axisY.z = 0.0;
  58599. this._cam_axisZ.x = 0.0;
  58600. this._cam_axisZ.y = 0.0;
  58601. this._cam_axisZ.z = 1.0;
  58602. // cases when the World Matrix is to be computed first
  58603. if (this.billboard || this._depthSort) {
  58604. this.mesh.computeWorldMatrix(true);
  58605. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58606. }
  58607. // if the particles will always face the camera
  58608. if (this.billboard) {
  58609. // compute the camera position and un-rotate it by the current mesh rotation
  58610. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58611. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58612. this._cam_axisZ.normalize();
  58613. // same for camera up vector extracted from the cam view matrix
  58614. var view = this._camera.getViewMatrix(true);
  58615. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58616. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58617. this._cam_axisY.normalize();
  58618. this._cam_axisX.normalize();
  58619. }
  58620. // if depthSort, compute the camera global position in the mesh local system
  58621. if (this._depthSort) {
  58622. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58623. }
  58624. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58625. var idx = 0; // current position index in the global array positions32
  58626. var index = 0; // position start index in the global array positions32 of the current particle
  58627. var colidx = 0; // current color index in the global array colors32
  58628. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58629. var uvidx = 0; // current uv index in the global array uvs32
  58630. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58631. var pt = 0; // current index in the particle model shape
  58632. if (this.mesh.isFacetDataEnabled) {
  58633. this._computeBoundingBox = true;
  58634. }
  58635. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58636. if (this._computeBoundingBox) {
  58637. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58638. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58639. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58640. }
  58641. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58642. if (this.mesh._boundingInfo) {
  58643. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58644. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58645. }
  58646. }
  58647. }
  58648. // particle loop
  58649. index = this.particles[start]._pos;
  58650. var vpos = (index / 3) | 0;
  58651. colorIndex = vpos * 4;
  58652. uvIndex = vpos * 2;
  58653. for (var p = start; p <= end; p++) {
  58654. this._particle = this.particles[p];
  58655. this._shape = this._particle._model._shape;
  58656. this._shapeUV = this._particle._model._shapeUV;
  58657. // call to custom user function to update the particle properties
  58658. this.updateParticle(this._particle);
  58659. // camera-particle distance for depth sorting
  58660. if (this._depthSort && this._depthSortParticles) {
  58661. var dsp = this.depthSortedParticles[p];
  58662. dsp.ind = this._particle._ind;
  58663. dsp.indicesLength = this._particle._model._indicesLength;
  58664. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58665. }
  58666. // skip the computations for inactive or already invisible particles
  58667. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58668. // increment indexes for the next particle
  58669. pt = this._shape.length;
  58670. index += pt * 3;
  58671. colorIndex += pt * 4;
  58672. uvIndex += pt * 2;
  58673. continue;
  58674. }
  58675. if (this._particle.isVisible) {
  58676. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58677. this._particleHasParent = (this._particle.parentId !== null);
  58678. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58679. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58680. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58681. // particle rotation matrix
  58682. if (this.billboard) {
  58683. this._particle.rotation.x = 0.0;
  58684. this._particle.rotation.y = 0.0;
  58685. }
  58686. if (this._computeParticleRotation || this.billboard) {
  58687. if (this._particle.rotationQuaternion) {
  58688. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58689. }
  58690. else {
  58691. this._yaw = this._particle.rotation.y;
  58692. this._pitch = this._particle.rotation.x;
  58693. this._roll = this._particle.rotation.z;
  58694. this._quaternionRotationYPR();
  58695. }
  58696. this._quaternionToRotationMatrix();
  58697. }
  58698. if (this._particleHasParent) {
  58699. this._parent = this.particles[this._particle.parentId];
  58700. 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];
  58701. 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];
  58702. 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];
  58703. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58704. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58705. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58706. if (this._computeParticleRotation || this.billboard) {
  58707. 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];
  58708. 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];
  58709. 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];
  58710. 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];
  58711. 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];
  58712. 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];
  58713. 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];
  58714. 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];
  58715. 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];
  58716. }
  58717. }
  58718. else {
  58719. this._particle._globalPosition.x = this._particle.position.x;
  58720. this._particle._globalPosition.y = this._particle.position.y;
  58721. this._particle._globalPosition.z = this._particle.position.z;
  58722. if (this._computeParticleRotation || this.billboard) {
  58723. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58724. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58725. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58726. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58727. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58728. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58729. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58730. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58731. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58732. }
  58733. }
  58734. if (this._particle.translateFromPivot) {
  58735. this._pivotBackTranslation.x = 0.0;
  58736. this._pivotBackTranslation.y = 0.0;
  58737. this._pivotBackTranslation.z = 0.0;
  58738. }
  58739. else {
  58740. this._pivotBackTranslation.x = this._scaledPivot.x;
  58741. this._pivotBackTranslation.y = this._scaledPivot.y;
  58742. this._pivotBackTranslation.z = this._scaledPivot.z;
  58743. }
  58744. // particle vertex loop
  58745. for (pt = 0; pt < this._shape.length; pt++) {
  58746. idx = index + pt * 3;
  58747. colidx = colorIndex + pt * 4;
  58748. uvidx = uvIndex + pt * 2;
  58749. this._vertex.x = this._shape[pt].x;
  58750. this._vertex.y = this._shape[pt].y;
  58751. this._vertex.z = this._shape[pt].z;
  58752. if (this._computeParticleVertex) {
  58753. this.updateParticleVertex(this._particle, this._vertex, pt);
  58754. }
  58755. // positions
  58756. this._vertex.x *= this._particle.scaling.x;
  58757. this._vertex.y *= this._particle.scaling.y;
  58758. this._vertex.z *= this._particle.scaling.z;
  58759. this._vertex.x -= this._scaledPivot.x;
  58760. this._vertex.y -= this._scaledPivot.y;
  58761. this._vertex.z -= this._scaledPivot.z;
  58762. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58763. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58764. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58765. this._rotated.x += this._pivotBackTranslation.x;
  58766. this._rotated.y += this._pivotBackTranslation.y;
  58767. this._rotated.z += this._pivotBackTranslation.z;
  58768. 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;
  58769. 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;
  58770. 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;
  58771. if (this._computeBoundingBox) {
  58772. if (this._positions32[idx] < this._minimum.x) {
  58773. this._minimum.x = this._positions32[idx];
  58774. }
  58775. if (this._positions32[idx] > this._maximum.x) {
  58776. this._maximum.x = this._positions32[idx];
  58777. }
  58778. if (this._positions32[idx + 1] < this._minimum.y) {
  58779. this._minimum.y = this._positions32[idx + 1];
  58780. }
  58781. if (this._positions32[idx + 1] > this._maximum.y) {
  58782. this._maximum.y = this._positions32[idx + 1];
  58783. }
  58784. if (this._positions32[idx + 2] < this._minimum.z) {
  58785. this._minimum.z = this._positions32[idx + 2];
  58786. }
  58787. if (this._positions32[idx + 2] > this._maximum.z) {
  58788. this._maximum.z = this._positions32[idx + 2];
  58789. }
  58790. }
  58791. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58792. if (!this._computeParticleVertex) {
  58793. this._normal.x = this._fixedNormal32[idx];
  58794. this._normal.y = this._fixedNormal32[idx + 1];
  58795. this._normal.z = this._fixedNormal32[idx + 2];
  58796. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58797. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58798. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58799. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58800. 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;
  58801. 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;
  58802. }
  58803. if (this._computeParticleColor && this._particle.color) {
  58804. this._colors32[colidx] = this._particle.color.r;
  58805. this._colors32[colidx + 1] = this._particle.color.g;
  58806. this._colors32[colidx + 2] = this._particle.color.b;
  58807. this._colors32[colidx + 3] = this._particle.color.a;
  58808. }
  58809. if (this._computeParticleTexture) {
  58810. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58811. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58812. }
  58813. }
  58814. }
  58815. // particle just set invisible : scaled to zero and positioned at the origin
  58816. else {
  58817. this._particle._stillInvisible = true; // mark the particle as invisible
  58818. for (pt = 0; pt < this._shape.length; pt++) {
  58819. idx = index + pt * 3;
  58820. colidx = colorIndex + pt * 4;
  58821. uvidx = uvIndex + pt * 2;
  58822. this._positions32[idx] = 0.0;
  58823. this._positions32[idx + 1] = 0.0;
  58824. this._positions32[idx + 2] = 0.0;
  58825. this._normals32[idx] = 0.0;
  58826. this._normals32[idx + 1] = 0.0;
  58827. this._normals32[idx + 2] = 0.0;
  58828. if (this._computeParticleColor && this._particle.color) {
  58829. this._colors32[colidx] = this._particle.color.r;
  58830. this._colors32[colidx + 1] = this._particle.color.g;
  58831. this._colors32[colidx + 2] = this._particle.color.b;
  58832. this._colors32[colidx + 3] = this._particle.color.a;
  58833. }
  58834. if (this._computeParticleTexture) {
  58835. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58836. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58837. }
  58838. }
  58839. }
  58840. // if the particle intersections must be computed : update the bbInfo
  58841. if (this._particlesIntersect) {
  58842. var bInfo = this._particle._boundingInfo;
  58843. var bBox = bInfo.boundingBox;
  58844. var bSphere = bInfo.boundingSphere;
  58845. if (!this._bSphereOnly) {
  58846. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58847. for (var b = 0; b < bBox.vectors.length; b++) {
  58848. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58849. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58850. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58851. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58852. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58853. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58854. 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;
  58855. 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;
  58856. 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;
  58857. }
  58858. bBox._update(this.mesh._worldMatrix);
  58859. }
  58860. // place and scale the particle bouding sphere in the SPS local system, then update it
  58861. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58862. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58863. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58864. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58865. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58866. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58867. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58868. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58869. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58870. 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));
  58871. bSphere._update(this.mesh._worldMatrix);
  58872. }
  58873. // increment indexes for the next particle
  58874. index = idx + 3;
  58875. colorIndex = colidx + 4;
  58876. uvIndex = uvidx + 2;
  58877. }
  58878. // if the VBO must be updated
  58879. if (update) {
  58880. if (this._computeParticleColor) {
  58881. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58882. }
  58883. if (this._computeParticleTexture) {
  58884. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58885. }
  58886. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58887. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58888. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58889. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58890. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58891. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58892. for (var i = 0; i < this._normals32.length; i++) {
  58893. this._fixedNormal32[i] = this._normals32[i];
  58894. }
  58895. }
  58896. if (!this.mesh.areNormalsFrozen) {
  58897. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58898. }
  58899. }
  58900. if (this._depthSort && this._depthSortParticles) {
  58901. this.depthSortedParticles.sort(this._depthSortFunction);
  58902. var dspl = this.depthSortedParticles.length;
  58903. var sorted = 0;
  58904. var lind = 0;
  58905. var sind = 0;
  58906. var sid = 0;
  58907. for (sorted = 0; sorted < dspl; sorted++) {
  58908. lind = this.depthSortedParticles[sorted].indicesLength;
  58909. sind = this.depthSortedParticles[sorted].ind;
  58910. for (var i = 0; i < lind; i++) {
  58911. this._indices32[sid] = this._indices[sind + i];
  58912. sid++;
  58913. }
  58914. }
  58915. this.mesh.updateIndices(this._indices32);
  58916. }
  58917. }
  58918. if (this._computeBoundingBox) {
  58919. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58920. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58921. }
  58922. this.afterUpdateParticles(start, end, update);
  58923. return this;
  58924. };
  58925. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58926. this._halfroll = this._roll * 0.5;
  58927. this._halfpitch = this._pitch * 0.5;
  58928. this._halfyaw = this._yaw * 0.5;
  58929. this._sinRoll = Math.sin(this._halfroll);
  58930. this._cosRoll = Math.cos(this._halfroll);
  58931. this._sinPitch = Math.sin(this._halfpitch);
  58932. this._cosPitch = Math.cos(this._halfpitch);
  58933. this._sinYaw = Math.sin(this._halfyaw);
  58934. this._cosYaw = Math.cos(this._halfyaw);
  58935. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58936. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58937. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58938. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58939. };
  58940. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58941. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58942. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58943. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58944. this._rotMatrix.m[3] = 0;
  58945. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58946. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58947. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58948. this._rotMatrix.m[7] = 0;
  58949. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58950. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58951. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58952. this._rotMatrix.m[11] = 0;
  58953. this._rotMatrix.m[12] = 0;
  58954. this._rotMatrix.m[13] = 0;
  58955. this._rotMatrix.m[14] = 0;
  58956. this._rotMatrix.m[15] = 1.0;
  58957. };
  58958. /**
  58959. * Disposes the SPS.
  58960. */
  58961. SolidParticleSystem.prototype.dispose = function () {
  58962. this.mesh.dispose();
  58963. this.vars = null;
  58964. // drop references to internal big arrays for the GC
  58965. this._positions = null;
  58966. this._indices = null;
  58967. this._normals = null;
  58968. this._uvs = null;
  58969. this._colors = null;
  58970. this._indices32 = null;
  58971. this._positions32 = null;
  58972. this._normals32 = null;
  58973. this._fixedNormal32 = null;
  58974. this._uvs32 = null;
  58975. this._colors32 = null;
  58976. this.pickedParticles = null;
  58977. };
  58978. /**
  58979. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58980. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58981. * @returns the SPS.
  58982. */
  58983. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58984. if (!this._isVisibilityBoxLocked) {
  58985. this.mesh.refreshBoundingInfo();
  58986. }
  58987. return this;
  58988. };
  58989. /**
  58990. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58991. * @param size the size (float) of the visibility box
  58992. * note : this doesn't lock the SPS mesh bounding box.
  58993. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58994. */
  58995. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58996. var vis = size / 2;
  58997. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58998. };
  58999. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59000. /**
  59001. * Gets whether the SPS as always visible or not
  59002. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59003. */
  59004. get: function () {
  59005. return this._alwaysVisible;
  59006. },
  59007. /**
  59008. * Sets the SPS as always visible or not
  59009. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59010. */
  59011. set: function (val) {
  59012. this._alwaysVisible = val;
  59013. this.mesh.alwaysSelectAsActiveMesh = val;
  59014. },
  59015. enumerable: true,
  59016. configurable: true
  59017. });
  59018. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59019. /**
  59020. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59021. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59022. */
  59023. get: function () {
  59024. return this._isVisibilityBoxLocked;
  59025. },
  59026. /**
  59027. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59028. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59029. */
  59030. set: function (val) {
  59031. this._isVisibilityBoxLocked = val;
  59032. var boundingInfo = this.mesh.getBoundingInfo();
  59033. boundingInfo.isLocked = val;
  59034. },
  59035. enumerable: true,
  59036. configurable: true
  59037. });
  59038. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59039. /**
  59040. * Gets if `setParticles()` computes the particle rotations or not.
  59041. * Default value : true. The SPS is faster when it's set to false.
  59042. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59043. */
  59044. get: function () {
  59045. return this._computeParticleRotation;
  59046. },
  59047. /**
  59048. * Tells to `setParticles()` to compute the particle rotations or not.
  59049. * Default value : true. The SPS is faster when it's set to false.
  59050. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59051. */
  59052. set: function (val) {
  59053. this._computeParticleRotation = val;
  59054. },
  59055. enumerable: true,
  59056. configurable: true
  59057. });
  59058. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59059. /**
  59060. * Gets if `setParticles()` computes the particle colors or not.
  59061. * Default value : true. The SPS is faster when it's set to false.
  59062. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59063. */
  59064. get: function () {
  59065. return this._computeParticleColor;
  59066. },
  59067. /**
  59068. * Tells to `setParticles()` to compute the particle colors or not.
  59069. * Default value : true. The SPS is faster when it's set to false.
  59070. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59071. */
  59072. set: function (val) {
  59073. this._computeParticleColor = val;
  59074. },
  59075. enumerable: true,
  59076. configurable: true
  59077. });
  59078. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59079. /**
  59080. * Gets if `setParticles()` computes the particle textures or not.
  59081. * Default value : true. The SPS is faster when it's set to false.
  59082. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59083. */
  59084. get: function () {
  59085. return this._computeParticleTexture;
  59086. },
  59087. set: function (val) {
  59088. this._computeParticleTexture = val;
  59089. },
  59090. enumerable: true,
  59091. configurable: true
  59092. });
  59093. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59094. /**
  59095. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59096. * Default value : false. The SPS is faster when it's set to false.
  59097. * Note : the particle custom vertex positions aren't stored values.
  59098. */
  59099. get: function () {
  59100. return this._computeParticleVertex;
  59101. },
  59102. /**
  59103. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59104. * Default value : false. The SPS is faster when it's set to false.
  59105. * Note : the particle custom vertex positions aren't stored values.
  59106. */
  59107. set: function (val) {
  59108. this._computeParticleVertex = val;
  59109. },
  59110. enumerable: true,
  59111. configurable: true
  59112. });
  59113. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59114. /**
  59115. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59116. */
  59117. get: function () {
  59118. return this._computeBoundingBox;
  59119. },
  59120. /**
  59121. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59122. */
  59123. set: function (val) {
  59124. this._computeBoundingBox = val;
  59125. },
  59126. enumerable: true,
  59127. configurable: true
  59128. });
  59129. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59130. /**
  59131. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59132. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59133. * Default : `true`
  59134. */
  59135. get: function () {
  59136. return this._depthSortParticles;
  59137. },
  59138. /**
  59139. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59140. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59141. * Default : `true`
  59142. */
  59143. set: function (val) {
  59144. this._depthSortParticles = val;
  59145. },
  59146. enumerable: true,
  59147. configurable: true
  59148. });
  59149. // =======================================================================
  59150. // Particle behavior logic
  59151. // these following methods may be overwritten by the user to fit his needs
  59152. /**
  59153. * This function does nothing. It may be overwritten to set all the particle first values.
  59154. * The SPS doesn't call this function, you may have to call it by your own.
  59155. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59156. */
  59157. SolidParticleSystem.prototype.initParticles = function () {
  59158. };
  59159. /**
  59160. * This function does nothing. It may be overwritten to recycle a particle.
  59161. * The SPS doesn't call this function, you may have to call it by your own.
  59162. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59163. * @param particle The particle to recycle
  59164. * @returns the recycled particle
  59165. */
  59166. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59167. return particle;
  59168. };
  59169. /**
  59170. * Updates a particle : this function should be overwritten by the user.
  59171. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59172. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59173. * @example : just set a particle position or velocity and recycle conditions
  59174. * @param particle The particle to update
  59175. * @returns the updated particle
  59176. */
  59177. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59178. return particle;
  59179. };
  59180. /**
  59181. * Updates a vertex of a particle : it can be overwritten by the user.
  59182. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59183. * @param particle the current particle
  59184. * @param vertex the current index of the current particle
  59185. * @param pt the index of the current vertex in the particle shape
  59186. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59187. * @example : just set a vertex particle position
  59188. * @returns the updated vertex
  59189. */
  59190. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59191. return vertex;
  59192. };
  59193. /**
  59194. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59195. * This does nothing and may be overwritten by the user.
  59196. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59197. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59198. * @param update the boolean update value actually passed to setParticles()
  59199. */
  59200. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59201. };
  59202. /**
  59203. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59204. * This will be passed three parameters.
  59205. * This does nothing and may be overwritten by the user.
  59206. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59207. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59208. * @param update the boolean update value actually passed to setParticles()
  59209. */
  59210. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59211. };
  59212. return SolidParticleSystem;
  59213. }());
  59214. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59215. })(BABYLON || (BABYLON = {}));
  59216. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59217. var BABYLON;
  59218. (function (BABYLON) {
  59219. var ShaderMaterial = /** @class */ (function (_super) {
  59220. __extends(ShaderMaterial, _super);
  59221. function ShaderMaterial(name, scene, shaderPath, options) {
  59222. var _this = _super.call(this, name, scene) || this;
  59223. _this._textures = {};
  59224. _this._textureArrays = {};
  59225. _this._floats = {};
  59226. _this._ints = {};
  59227. _this._floatsArrays = {};
  59228. _this._colors3 = {};
  59229. _this._colors3Arrays = {};
  59230. _this._colors4 = {};
  59231. _this._vectors2 = {};
  59232. _this._vectors3 = {};
  59233. _this._vectors4 = {};
  59234. _this._matrices = {};
  59235. _this._matrices3x3 = {};
  59236. _this._matrices2x2 = {};
  59237. _this._vectors2Arrays = {};
  59238. _this._vectors3Arrays = {};
  59239. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59240. _this._shaderPath = shaderPath;
  59241. options.needAlphaBlending = options.needAlphaBlending || false;
  59242. options.needAlphaTesting = options.needAlphaTesting || false;
  59243. options.attributes = options.attributes || ["position", "normal", "uv"];
  59244. options.uniforms = options.uniforms || ["worldViewProjection"];
  59245. options.uniformBuffers = options.uniformBuffers || [];
  59246. options.samplers = options.samplers || [];
  59247. options.defines = options.defines || [];
  59248. _this._options = options;
  59249. return _this;
  59250. }
  59251. ShaderMaterial.prototype.getClassName = function () {
  59252. return "ShaderMaterial";
  59253. };
  59254. ShaderMaterial.prototype.needAlphaBlending = function () {
  59255. return this._options.needAlphaBlending;
  59256. };
  59257. ShaderMaterial.prototype.needAlphaTesting = function () {
  59258. return this._options.needAlphaTesting;
  59259. };
  59260. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59261. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59262. this._options.uniforms.push(uniformName);
  59263. }
  59264. };
  59265. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59266. if (this._options.samplers.indexOf(name) === -1) {
  59267. this._options.samplers.push(name);
  59268. }
  59269. this._textures[name] = texture;
  59270. return this;
  59271. };
  59272. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59273. if (this._options.samplers.indexOf(name) === -1) {
  59274. this._options.samplers.push(name);
  59275. }
  59276. this._checkUniform(name);
  59277. this._textureArrays[name] = textures;
  59278. return this;
  59279. };
  59280. ShaderMaterial.prototype.setFloat = function (name, value) {
  59281. this._checkUniform(name);
  59282. this._floats[name] = value;
  59283. return this;
  59284. };
  59285. ShaderMaterial.prototype.setInt = function (name, value) {
  59286. this._checkUniform(name);
  59287. this._ints[name] = value;
  59288. return this;
  59289. };
  59290. ShaderMaterial.prototype.setFloats = function (name, value) {
  59291. this._checkUniform(name);
  59292. this._floatsArrays[name] = value;
  59293. return this;
  59294. };
  59295. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59296. this._checkUniform(name);
  59297. this._colors3[name] = value;
  59298. return this;
  59299. };
  59300. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59301. this._checkUniform(name);
  59302. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59303. color.toArray(arr, arr.length);
  59304. return arr;
  59305. }, []);
  59306. return this;
  59307. };
  59308. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59309. this._checkUniform(name);
  59310. this._colors4[name] = value;
  59311. return this;
  59312. };
  59313. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59314. this._checkUniform(name);
  59315. this._vectors2[name] = value;
  59316. return this;
  59317. };
  59318. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59319. this._checkUniform(name);
  59320. this._vectors3[name] = value;
  59321. return this;
  59322. };
  59323. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59324. this._checkUniform(name);
  59325. this._vectors4[name] = value;
  59326. return this;
  59327. };
  59328. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59329. this._checkUniform(name);
  59330. this._matrices[name] = value;
  59331. return this;
  59332. };
  59333. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59334. this._checkUniform(name);
  59335. this._matrices3x3[name] = value;
  59336. return this;
  59337. };
  59338. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59339. this._checkUniform(name);
  59340. this._matrices2x2[name] = value;
  59341. return this;
  59342. };
  59343. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59344. this._checkUniform(name);
  59345. this._vectors2Arrays[name] = value;
  59346. return this;
  59347. };
  59348. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59349. this._checkUniform(name);
  59350. this._vectors3Arrays[name] = value;
  59351. return this;
  59352. };
  59353. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59354. if (!mesh) {
  59355. return true;
  59356. }
  59357. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59358. return false;
  59359. }
  59360. return false;
  59361. };
  59362. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59363. var scene = this.getScene();
  59364. var engine = scene.getEngine();
  59365. if (!this.checkReadyOnEveryCall) {
  59366. if (this._renderId === scene.getRenderId()) {
  59367. if (this._checkCache(scene, mesh, useInstances)) {
  59368. return true;
  59369. }
  59370. }
  59371. }
  59372. // Instances
  59373. var defines = [];
  59374. var attribs = [];
  59375. var fallbacks = new BABYLON.EffectFallbacks();
  59376. if (useInstances) {
  59377. defines.push("#define INSTANCES");
  59378. }
  59379. for (var index = 0; index < this._options.defines.length; index++) {
  59380. defines.push(this._options.defines[index]);
  59381. }
  59382. for (var index = 0; index < this._options.attributes.length; index++) {
  59383. attribs.push(this._options.attributes[index]);
  59384. }
  59385. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59386. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59387. defines.push("#define VERTEXCOLOR");
  59388. }
  59389. // Bones
  59390. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59391. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59392. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59393. if (mesh.numBoneInfluencers > 4) {
  59394. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59395. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59396. }
  59397. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59398. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59399. fallbacks.addCPUSkinningFallback(0, mesh);
  59400. if (this._options.uniforms.indexOf("mBones") === -1) {
  59401. this._options.uniforms.push("mBones");
  59402. }
  59403. }
  59404. else {
  59405. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59406. }
  59407. // Textures
  59408. for (var name in this._textures) {
  59409. if (!this._textures[name].isReady()) {
  59410. return false;
  59411. }
  59412. }
  59413. // Alpha test
  59414. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59415. defines.push("#define ALPHATEST");
  59416. }
  59417. var previousEffect = this._effect;
  59418. var join = defines.join("\n");
  59419. this._effect = engine.createEffect(this._shaderPath, {
  59420. attributes: attribs,
  59421. uniformsNames: this._options.uniforms,
  59422. uniformBuffersNames: this._options.uniformBuffers,
  59423. samplers: this._options.samplers,
  59424. defines: join,
  59425. fallbacks: fallbacks,
  59426. onCompiled: this.onCompiled,
  59427. onError: this.onError
  59428. }, engine);
  59429. if (!this._effect.isReady()) {
  59430. return false;
  59431. }
  59432. if (previousEffect !== this._effect) {
  59433. scene.resetCachedMaterial();
  59434. }
  59435. this._renderId = scene.getRenderId();
  59436. return true;
  59437. };
  59438. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59439. var scene = this.getScene();
  59440. if (!this._effect) {
  59441. return;
  59442. }
  59443. if (this._options.uniforms.indexOf("world") !== -1) {
  59444. this._effect.setMatrix("world", world);
  59445. }
  59446. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59447. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59448. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59449. }
  59450. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59451. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59452. }
  59453. };
  59454. ShaderMaterial.prototype.bind = function (world, mesh) {
  59455. // Std values
  59456. this.bindOnlyWorldMatrix(world);
  59457. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59458. if (this._options.uniforms.indexOf("view") !== -1) {
  59459. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59460. }
  59461. if (this._options.uniforms.indexOf("projection") !== -1) {
  59462. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59463. }
  59464. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59465. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59466. }
  59467. // Bones
  59468. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59469. var name;
  59470. // Texture
  59471. for (name in this._textures) {
  59472. this._effect.setTexture(name, this._textures[name]);
  59473. }
  59474. // Texture arrays
  59475. for (name in this._textureArrays) {
  59476. this._effect.setTextureArray(name, this._textureArrays[name]);
  59477. }
  59478. // Int
  59479. for (name in this._ints) {
  59480. this._effect.setInt(name, this._ints[name]);
  59481. }
  59482. // Float
  59483. for (name in this._floats) {
  59484. this._effect.setFloat(name, this._floats[name]);
  59485. }
  59486. // Floats
  59487. for (name in this._floatsArrays) {
  59488. this._effect.setArray(name, this._floatsArrays[name]);
  59489. }
  59490. // Color3
  59491. for (name in this._colors3) {
  59492. this._effect.setColor3(name, this._colors3[name]);
  59493. }
  59494. for (name in this._colors3Arrays) {
  59495. this._effect.setArray3(name, this._colors3Arrays[name]);
  59496. }
  59497. // Color4
  59498. for (name in this._colors4) {
  59499. var color = this._colors4[name];
  59500. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59501. }
  59502. // Vector2
  59503. for (name in this._vectors2) {
  59504. this._effect.setVector2(name, this._vectors2[name]);
  59505. }
  59506. // Vector3
  59507. for (name in this._vectors3) {
  59508. this._effect.setVector3(name, this._vectors3[name]);
  59509. }
  59510. // Vector4
  59511. for (name in this._vectors4) {
  59512. this._effect.setVector4(name, this._vectors4[name]);
  59513. }
  59514. // Matrix
  59515. for (name in this._matrices) {
  59516. this._effect.setMatrix(name, this._matrices[name]);
  59517. }
  59518. // Matrix 3x3
  59519. for (name in this._matrices3x3) {
  59520. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59521. }
  59522. // Matrix 2x2
  59523. for (name in this._matrices2x2) {
  59524. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59525. }
  59526. // Vector2Array
  59527. for (name in this._vectors2Arrays) {
  59528. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59529. }
  59530. // Vector3Array
  59531. for (name in this._vectors3Arrays) {
  59532. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59533. }
  59534. }
  59535. this._afterBind(mesh);
  59536. };
  59537. ShaderMaterial.prototype.getActiveTextures = function () {
  59538. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59539. for (var name in this._textures) {
  59540. activeTextures.push(this._textures[name]);
  59541. }
  59542. for (var name in this._textureArrays) {
  59543. var array = this._textureArrays[name];
  59544. for (var index = 0; index < array.length; index++) {
  59545. activeTextures.push(array[index]);
  59546. }
  59547. }
  59548. return activeTextures;
  59549. };
  59550. ShaderMaterial.prototype.hasTexture = function (texture) {
  59551. if (_super.prototype.hasTexture.call(this, texture)) {
  59552. return true;
  59553. }
  59554. for (var name in this._textures) {
  59555. if (this._textures[name] === texture) {
  59556. return true;
  59557. }
  59558. }
  59559. for (var name in this._textureArrays) {
  59560. var array = this._textureArrays[name];
  59561. for (var index = 0; index < array.length; index++) {
  59562. if (array[index] === texture) {
  59563. return true;
  59564. }
  59565. }
  59566. }
  59567. return false;
  59568. };
  59569. ShaderMaterial.prototype.clone = function (name) {
  59570. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59571. return newShaderMaterial;
  59572. };
  59573. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59574. if (forceDisposeTextures) {
  59575. var name;
  59576. for (name in this._textures) {
  59577. this._textures[name].dispose();
  59578. }
  59579. for (name in this._textureArrays) {
  59580. var array = this._textureArrays[name];
  59581. for (var index = 0; index < array.length; index++) {
  59582. array[index].dispose();
  59583. }
  59584. }
  59585. }
  59586. this._textures = {};
  59587. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59588. };
  59589. ShaderMaterial.prototype.serialize = function () {
  59590. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59591. serializationObject.customType = "BABYLON.ShaderMaterial";
  59592. serializationObject.options = this._options;
  59593. serializationObject.shaderPath = this._shaderPath;
  59594. var name;
  59595. // Texture
  59596. serializationObject.textures = {};
  59597. for (name in this._textures) {
  59598. serializationObject.textures[name] = this._textures[name].serialize();
  59599. }
  59600. // Texture arrays
  59601. serializationObject.textureArrays = {};
  59602. for (name in this._textureArrays) {
  59603. serializationObject.textureArrays[name] = [];
  59604. var array = this._textureArrays[name];
  59605. for (var index = 0; index < array.length; index++) {
  59606. serializationObject.textureArrays[name].push(array[index].serialize());
  59607. }
  59608. }
  59609. // Float
  59610. serializationObject.floats = {};
  59611. for (name in this._floats) {
  59612. serializationObject.floats[name] = this._floats[name];
  59613. }
  59614. // Float s
  59615. serializationObject.FloatArrays = {};
  59616. for (name in this._floatsArrays) {
  59617. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59618. }
  59619. // Color3
  59620. serializationObject.colors3 = {};
  59621. for (name in this._colors3) {
  59622. serializationObject.colors3[name] = this._colors3[name].asArray();
  59623. }
  59624. // Color3 array
  59625. serializationObject.colors3Arrays = {};
  59626. for (name in this._colors3Arrays) {
  59627. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59628. }
  59629. // Color4
  59630. serializationObject.colors4 = {};
  59631. for (name in this._colors4) {
  59632. serializationObject.colors4[name] = this._colors4[name].asArray();
  59633. }
  59634. // Vector2
  59635. serializationObject.vectors2 = {};
  59636. for (name in this._vectors2) {
  59637. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59638. }
  59639. // Vector3
  59640. serializationObject.vectors3 = {};
  59641. for (name in this._vectors3) {
  59642. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59643. }
  59644. // Vector4
  59645. serializationObject.vectors4 = {};
  59646. for (name in this._vectors4) {
  59647. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59648. }
  59649. // Matrix
  59650. serializationObject.matrices = {};
  59651. for (name in this._matrices) {
  59652. serializationObject.matrices[name] = this._matrices[name].asArray();
  59653. }
  59654. // Matrix 3x3
  59655. serializationObject.matrices3x3 = {};
  59656. for (name in this._matrices3x3) {
  59657. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59658. }
  59659. // Matrix 2x2
  59660. serializationObject.matrices2x2 = {};
  59661. for (name in this._matrices2x2) {
  59662. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59663. }
  59664. // Vector2Array
  59665. serializationObject.vectors2Arrays = {};
  59666. for (name in this._vectors2Arrays) {
  59667. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59668. }
  59669. // Vector3Array
  59670. serializationObject.vectors3Arrays = {};
  59671. for (name in this._vectors3Arrays) {
  59672. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59673. }
  59674. return serializationObject;
  59675. };
  59676. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59677. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59678. var name;
  59679. // Texture
  59680. for (name in source.textures) {
  59681. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59682. }
  59683. // Texture arrays
  59684. for (name in source.textureArrays) {
  59685. var array = source.textureArrays[name];
  59686. var textureArray = new Array();
  59687. for (var index = 0; index < array.length; index++) {
  59688. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59689. }
  59690. material.setTextureArray(name, textureArray);
  59691. }
  59692. // Float
  59693. for (name in source.floats) {
  59694. material.setFloat(name, source.floats[name]);
  59695. }
  59696. // Float s
  59697. for (name in source.floatsArrays) {
  59698. material.setFloats(name, source.floatsArrays[name]);
  59699. }
  59700. // Color3
  59701. for (name in source.colors3) {
  59702. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59703. }
  59704. // Color3 arrays
  59705. for (name in source.colors3Arrays) {
  59706. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59707. if (i % 3 === 0) {
  59708. arr.push([num]);
  59709. }
  59710. else {
  59711. arr[arr.length - 1].push(num);
  59712. }
  59713. return arr;
  59714. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59715. material.setColor3Array(name, colors);
  59716. }
  59717. // Color4
  59718. for (name in source.colors4) {
  59719. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59720. }
  59721. // Vector2
  59722. for (name in source.vectors2) {
  59723. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59724. }
  59725. // Vector3
  59726. for (name in source.vectors3) {
  59727. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59728. }
  59729. // Vector4
  59730. for (name in source.vectors4) {
  59731. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59732. }
  59733. // Matrix
  59734. for (name in source.matrices) {
  59735. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59736. }
  59737. // Matrix 3x3
  59738. for (name in source.matrices3x3) {
  59739. material.setMatrix3x3(name, source.matrices3x3[name]);
  59740. }
  59741. // Matrix 2x2
  59742. for (name in source.matrices2x2) {
  59743. material.setMatrix2x2(name, source.matrices2x2[name]);
  59744. }
  59745. // Vector2Array
  59746. for (name in source.vectors2Arrays) {
  59747. material.setArray2(name, source.vectors2Arrays[name]);
  59748. }
  59749. // Vector3Array
  59750. for (name in source.vectors3Arrays) {
  59751. material.setArray3(name, source.vectors3Arrays[name]);
  59752. }
  59753. return material;
  59754. };
  59755. return ShaderMaterial;
  59756. }(BABYLON.Material));
  59757. BABYLON.ShaderMaterial = ShaderMaterial;
  59758. })(BABYLON || (BABYLON = {}));
  59759. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59760. var BABYLON;
  59761. (function (BABYLON) {
  59762. var GroundMesh = /** @class */ (function (_super) {
  59763. __extends(GroundMesh, _super);
  59764. function GroundMesh(name, scene) {
  59765. var _this = _super.call(this, name, scene) || this;
  59766. _this.generateOctree = false;
  59767. return _this;
  59768. }
  59769. GroundMesh.prototype.getClassName = function () {
  59770. return "GroundMesh";
  59771. };
  59772. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59773. get: function () {
  59774. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59775. },
  59776. enumerable: true,
  59777. configurable: true
  59778. });
  59779. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59780. get: function () {
  59781. return this._subdivisionsX;
  59782. },
  59783. enumerable: true,
  59784. configurable: true
  59785. });
  59786. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59787. get: function () {
  59788. return this._subdivisionsY;
  59789. },
  59790. enumerable: true,
  59791. configurable: true
  59792. });
  59793. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59794. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59795. this._subdivisionsX = chunksCount;
  59796. this._subdivisionsY = chunksCount;
  59797. this.subdivide(chunksCount);
  59798. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59799. };
  59800. /**
  59801. * Returns a height (y) value in the Worl system :
  59802. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59803. * Returns the ground y position if (x, z) are outside the ground surface.
  59804. */
  59805. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59806. var world = this.getWorldMatrix();
  59807. var invMat = BABYLON.Tmp.Matrix[5];
  59808. world.invertToRef(invMat);
  59809. var tmpVect = BABYLON.Tmp.Vector3[8];
  59810. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59811. x = tmpVect.x;
  59812. z = tmpVect.z;
  59813. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59814. return this.position.y;
  59815. }
  59816. if (!this._heightQuads || this._heightQuads.length == 0) {
  59817. this._initHeightQuads();
  59818. this._computeHeightQuads();
  59819. }
  59820. var facet = this._getFacetAt(x, z);
  59821. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59822. // return y in the World system
  59823. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59824. return tmpVect.y;
  59825. };
  59826. /**
  59827. * Returns a normalized vector (Vector3) orthogonal to the ground
  59828. * at the ground coordinates (x, z) expressed in the World system.
  59829. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59830. */
  59831. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59832. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59833. this.getNormalAtCoordinatesToRef(x, z, normal);
  59834. return normal;
  59835. };
  59836. /**
  59837. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59838. * at the ground coordinates (x, z) expressed in the World system.
  59839. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59840. * Returns the GroundMesh.
  59841. */
  59842. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59843. var world = this.getWorldMatrix();
  59844. var tmpMat = BABYLON.Tmp.Matrix[5];
  59845. world.invertToRef(tmpMat);
  59846. var tmpVect = BABYLON.Tmp.Vector3[8];
  59847. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59848. x = tmpVect.x;
  59849. z = tmpVect.z;
  59850. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59851. return this;
  59852. }
  59853. if (!this._heightQuads || this._heightQuads.length == 0) {
  59854. this._initHeightQuads();
  59855. this._computeHeightQuads();
  59856. }
  59857. var facet = this._getFacetAt(x, z);
  59858. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59859. return this;
  59860. };
  59861. /**
  59862. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59863. * if the ground has been updated.
  59864. * This can be used in the render loop.
  59865. * Returns the GroundMesh.
  59866. */
  59867. GroundMesh.prototype.updateCoordinateHeights = function () {
  59868. if (!this._heightQuads || this._heightQuads.length == 0) {
  59869. this._initHeightQuads();
  59870. }
  59871. this._computeHeightQuads();
  59872. return this;
  59873. };
  59874. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59875. GroundMesh.prototype._getFacetAt = function (x, z) {
  59876. // retrieve col and row from x, z coordinates in the ground local system
  59877. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59878. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59879. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59880. var facet;
  59881. if (z < quad.slope.x * x + quad.slope.y) {
  59882. facet = quad.facet1;
  59883. }
  59884. else {
  59885. facet = quad.facet2;
  59886. }
  59887. return facet;
  59888. };
  59889. // Creates and populates the heightMap array with "facet" elements :
  59890. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59891. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59892. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59893. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59894. // Returns the GroundMesh.
  59895. GroundMesh.prototype._initHeightQuads = function () {
  59896. var subdivisionsX = this._subdivisionsX;
  59897. var subdivisionsY = this._subdivisionsY;
  59898. this._heightQuads = new Array();
  59899. for (var row = 0; row < subdivisionsY; row++) {
  59900. for (var col = 0; col < subdivisionsX; col++) {
  59901. 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) };
  59902. this._heightQuads[row * subdivisionsX + col] = quad;
  59903. }
  59904. }
  59905. return this;
  59906. };
  59907. // Compute each quad element values and update the the heightMap array :
  59908. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59909. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59910. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59911. // Returns the GroundMesh.
  59912. GroundMesh.prototype._computeHeightQuads = function () {
  59913. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59914. if (!positions) {
  59915. return this;
  59916. }
  59917. var v1 = BABYLON.Tmp.Vector3[3];
  59918. var v2 = BABYLON.Tmp.Vector3[2];
  59919. var v3 = BABYLON.Tmp.Vector3[1];
  59920. var v4 = BABYLON.Tmp.Vector3[0];
  59921. var v1v2 = BABYLON.Tmp.Vector3[4];
  59922. var v1v3 = BABYLON.Tmp.Vector3[5];
  59923. var v1v4 = BABYLON.Tmp.Vector3[6];
  59924. var norm1 = BABYLON.Tmp.Vector3[7];
  59925. var norm2 = BABYLON.Tmp.Vector3[8];
  59926. var i = 0;
  59927. var j = 0;
  59928. var k = 0;
  59929. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59930. var h = 0;
  59931. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59932. var d2 = 0;
  59933. var subdivisionsX = this._subdivisionsX;
  59934. var subdivisionsY = this._subdivisionsY;
  59935. for (var row = 0; row < subdivisionsY; row++) {
  59936. for (var col = 0; col < subdivisionsX; col++) {
  59937. i = col * 3;
  59938. j = row * (subdivisionsX + 1) * 3;
  59939. k = (row + 1) * (subdivisionsX + 1) * 3;
  59940. v1.x = positions[j + i];
  59941. v1.y = positions[j + i + 1];
  59942. v1.z = positions[j + i + 2];
  59943. v2.x = positions[j + i + 3];
  59944. v2.y = positions[j + i + 4];
  59945. v2.z = positions[j + i + 5];
  59946. v3.x = positions[k + i];
  59947. v3.y = positions[k + i + 1];
  59948. v3.z = positions[k + i + 2];
  59949. v4.x = positions[k + i + 3];
  59950. v4.y = positions[k + i + 4];
  59951. v4.z = positions[k + i + 5];
  59952. // 2D slope V1V4
  59953. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59954. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59955. // facet equations :
  59956. // we compute each facet normal vector
  59957. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59958. // we compute the value d by applying the equation to v1 which belongs to the plane
  59959. // then we store the facet equation in a Vector4
  59960. v2.subtractToRef(v1, v1v2);
  59961. v3.subtractToRef(v1, v1v3);
  59962. v4.subtractToRef(v1, v1v4);
  59963. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59964. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59965. norm1.normalize();
  59966. norm2.normalize();
  59967. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59968. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59969. var quad = this._heightQuads[row * subdivisionsX + col];
  59970. quad.slope.copyFromFloats(cd, h);
  59971. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59972. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59973. }
  59974. }
  59975. return this;
  59976. };
  59977. GroundMesh.prototype.serialize = function (serializationObject) {
  59978. _super.prototype.serialize.call(this, serializationObject);
  59979. serializationObject.subdivisionsX = this._subdivisionsX;
  59980. serializationObject.subdivisionsY = this._subdivisionsY;
  59981. serializationObject.minX = this._minX;
  59982. serializationObject.maxX = this._maxX;
  59983. serializationObject.minZ = this._minZ;
  59984. serializationObject.maxZ = this._maxZ;
  59985. serializationObject.width = this._width;
  59986. serializationObject.height = this._height;
  59987. };
  59988. GroundMesh.Parse = function (parsedMesh, scene) {
  59989. var result = new GroundMesh(parsedMesh.name, scene);
  59990. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59991. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59992. result._minX = parsedMesh.minX;
  59993. result._maxX = parsedMesh.maxX;
  59994. result._minZ = parsedMesh.minZ;
  59995. result._maxZ = parsedMesh.maxZ;
  59996. result._width = parsedMesh.width;
  59997. result._height = parsedMesh.height;
  59998. return result;
  59999. };
  60000. return GroundMesh;
  60001. }(BABYLON.Mesh));
  60002. BABYLON.GroundMesh = GroundMesh;
  60003. })(BABYLON || (BABYLON = {}));
  60004. //# sourceMappingURL=babylon.groundMesh.js.map
  60005. var BABYLON;
  60006. (function (BABYLON) {
  60007. /**
  60008. * Creates an instance based on a source mesh.
  60009. */
  60010. var InstancedMesh = /** @class */ (function (_super) {
  60011. __extends(InstancedMesh, _super);
  60012. function InstancedMesh(name, source) {
  60013. var _this = _super.call(this, name, source.getScene()) || this;
  60014. source.instances.push(_this);
  60015. _this._sourceMesh = source;
  60016. _this.position.copyFrom(source.position);
  60017. _this.rotation.copyFrom(source.rotation);
  60018. _this.scaling.copyFrom(source.scaling);
  60019. if (source.rotationQuaternion) {
  60020. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60021. }
  60022. _this.infiniteDistance = source.infiniteDistance;
  60023. _this.setPivotMatrix(source.getPivotMatrix());
  60024. _this.refreshBoundingInfo();
  60025. _this._syncSubMeshes();
  60026. return _this;
  60027. }
  60028. /**
  60029. * Returns the string "InstancedMesh".
  60030. */
  60031. InstancedMesh.prototype.getClassName = function () {
  60032. return "InstancedMesh";
  60033. };
  60034. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60035. // Methods
  60036. get: function () {
  60037. return this._sourceMesh.receiveShadows;
  60038. },
  60039. enumerable: true,
  60040. configurable: true
  60041. });
  60042. Object.defineProperty(InstancedMesh.prototype, "material", {
  60043. get: function () {
  60044. return this._sourceMesh.material;
  60045. },
  60046. enumerable: true,
  60047. configurable: true
  60048. });
  60049. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60050. get: function () {
  60051. return this._sourceMesh.visibility;
  60052. },
  60053. enumerable: true,
  60054. configurable: true
  60055. });
  60056. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60057. get: function () {
  60058. return this._sourceMesh.skeleton;
  60059. },
  60060. enumerable: true,
  60061. configurable: true
  60062. });
  60063. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60064. get: function () {
  60065. return this._sourceMesh.renderingGroupId;
  60066. },
  60067. set: function (value) {
  60068. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60069. return;
  60070. }
  60071. //no-op with warning
  60072. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60073. },
  60074. enumerable: true,
  60075. configurable: true
  60076. });
  60077. /**
  60078. * Returns the total number of vertices (integer).
  60079. */
  60080. InstancedMesh.prototype.getTotalVertices = function () {
  60081. return this._sourceMesh.getTotalVertices();
  60082. };
  60083. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60084. get: function () {
  60085. return this._sourceMesh;
  60086. },
  60087. enumerable: true,
  60088. configurable: true
  60089. });
  60090. /**
  60091. * Is this node ready to be used/rendered
  60092. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60093. * @return {boolean} is it ready
  60094. */
  60095. InstancedMesh.prototype.isReady = function (completeCheck) {
  60096. if (completeCheck === void 0) { completeCheck = false; }
  60097. return this._sourceMesh.isReady(completeCheck, true);
  60098. };
  60099. /**
  60100. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60101. */
  60102. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60103. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60104. };
  60105. /**
  60106. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60107. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60108. * The `data` are either a numeric array either a Float32Array.
  60109. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60110. * 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).
  60111. * Note that a new underlying VertexBuffer object is created each call.
  60112. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60113. *
  60114. * Possible `kind` values :
  60115. * - BABYLON.VertexBuffer.PositionKind
  60116. * - BABYLON.VertexBuffer.UVKind
  60117. * - BABYLON.VertexBuffer.UV2Kind
  60118. * - BABYLON.VertexBuffer.UV3Kind
  60119. * - BABYLON.VertexBuffer.UV4Kind
  60120. * - BABYLON.VertexBuffer.UV5Kind
  60121. * - BABYLON.VertexBuffer.UV6Kind
  60122. * - BABYLON.VertexBuffer.ColorKind
  60123. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60124. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60125. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60126. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60127. *
  60128. * Returns the Mesh.
  60129. */
  60130. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60131. if (this.sourceMesh) {
  60132. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60133. }
  60134. return this.sourceMesh;
  60135. };
  60136. /**
  60137. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60138. * If the mesh has no geometry, it is simply returned as it is.
  60139. * The `data` are either a numeric array either a Float32Array.
  60140. * No new underlying VertexBuffer object is created.
  60141. * 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.
  60142. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60143. *
  60144. * Possible `kind` values :
  60145. * - BABYLON.VertexBuffer.PositionKind
  60146. * - BABYLON.VertexBuffer.UVKind
  60147. * - BABYLON.VertexBuffer.UV2Kind
  60148. * - BABYLON.VertexBuffer.UV3Kind
  60149. * - BABYLON.VertexBuffer.UV4Kind
  60150. * - BABYLON.VertexBuffer.UV5Kind
  60151. * - BABYLON.VertexBuffer.UV6Kind
  60152. * - BABYLON.VertexBuffer.ColorKind
  60153. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60154. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60155. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60156. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60157. *
  60158. * Returns the Mesh.
  60159. */
  60160. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60161. if (this.sourceMesh) {
  60162. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60163. }
  60164. return this.sourceMesh;
  60165. };
  60166. /**
  60167. * Sets the mesh indices.
  60168. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60169. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60170. * This method creates a new index buffer each call.
  60171. * Returns the Mesh.
  60172. */
  60173. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60174. if (totalVertices === void 0) { totalVertices = null; }
  60175. if (this.sourceMesh) {
  60176. this.sourceMesh.setIndices(indices, totalVertices);
  60177. }
  60178. return this.sourceMesh;
  60179. };
  60180. /**
  60181. * Boolean : True if the mesh owns the requested kind of data.
  60182. */
  60183. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60184. return this._sourceMesh.isVerticesDataPresent(kind);
  60185. };
  60186. /**
  60187. * Returns an array of indices (IndicesArray).
  60188. */
  60189. InstancedMesh.prototype.getIndices = function () {
  60190. return this._sourceMesh.getIndices();
  60191. };
  60192. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60193. get: function () {
  60194. return this._sourceMesh._positions;
  60195. },
  60196. enumerable: true,
  60197. configurable: true
  60198. });
  60199. /**
  60200. * Sets a new updated BoundingInfo to the mesh.
  60201. * Returns the mesh.
  60202. */
  60203. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60204. var meshBB = this._sourceMesh.getBoundingInfo();
  60205. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60206. this._updateBoundingInfo();
  60207. return this;
  60208. };
  60209. InstancedMesh.prototype._preActivate = function () {
  60210. if (this._currentLOD) {
  60211. this._currentLOD._preActivate();
  60212. }
  60213. return this;
  60214. };
  60215. InstancedMesh.prototype._activate = function (renderId) {
  60216. if (this._currentLOD) {
  60217. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60218. }
  60219. return this;
  60220. };
  60221. /**
  60222. * Returns the current associated LOD AbstractMesh.
  60223. */
  60224. InstancedMesh.prototype.getLOD = function (camera) {
  60225. if (!camera) {
  60226. return this;
  60227. }
  60228. var boundingInfo = this.getBoundingInfo();
  60229. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60230. if (this._currentLOD === this.sourceMesh) {
  60231. return this;
  60232. }
  60233. return this._currentLOD;
  60234. };
  60235. InstancedMesh.prototype._syncSubMeshes = function () {
  60236. this.releaseSubMeshes();
  60237. if (this._sourceMesh.subMeshes) {
  60238. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60239. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60240. }
  60241. }
  60242. return this;
  60243. };
  60244. InstancedMesh.prototype._generatePointsArray = function () {
  60245. return this._sourceMesh._generatePointsArray();
  60246. };
  60247. /**
  60248. * Creates a new InstancedMesh from the current mesh.
  60249. * - name (string) : the cloned mesh name
  60250. * - newParent (optional Node) : the optional Node to parent the clone to.
  60251. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60252. *
  60253. * Returns the clone.
  60254. */
  60255. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60256. var result = this._sourceMesh.createInstance(name);
  60257. // Deep copy
  60258. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60259. // Bounding info
  60260. this.refreshBoundingInfo();
  60261. // Parent
  60262. if (newParent) {
  60263. result.parent = newParent;
  60264. }
  60265. if (!doNotCloneChildren) {
  60266. // Children
  60267. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60268. var mesh = this.getScene().meshes[index];
  60269. if (mesh.parent === this) {
  60270. mesh.clone(mesh.name, result);
  60271. }
  60272. }
  60273. }
  60274. result.computeWorldMatrix(true);
  60275. return result;
  60276. };
  60277. /**
  60278. * Disposes the InstancedMesh.
  60279. * Returns nothing.
  60280. */
  60281. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60282. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60283. // Remove from mesh
  60284. var index = this._sourceMesh.instances.indexOf(this);
  60285. this._sourceMesh.instances.splice(index, 1);
  60286. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60287. };
  60288. return InstancedMesh;
  60289. }(BABYLON.AbstractMesh));
  60290. BABYLON.InstancedMesh = InstancedMesh;
  60291. })(BABYLON || (BABYLON = {}));
  60292. //# sourceMappingURL=babylon.instancedMesh.js.map
  60293. var BABYLON;
  60294. (function (BABYLON) {
  60295. var LinesMesh = /** @class */ (function (_super) {
  60296. __extends(LinesMesh, _super);
  60297. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60298. if (scene === void 0) { scene = null; }
  60299. if (parent === void 0) { parent = null; }
  60300. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60301. _this.useVertexColor = useVertexColor;
  60302. _this.useVertexAlpha = useVertexAlpha;
  60303. _this.color = new BABYLON.Color3(1, 1, 1);
  60304. _this.alpha = 1;
  60305. if (source) {
  60306. _this.color = source.color.clone();
  60307. _this.alpha = source.alpha;
  60308. _this.useVertexColor = source.useVertexColor;
  60309. _this.useVertexAlpha = source.useVertexAlpha;
  60310. }
  60311. _this._intersectionThreshold = 0.1;
  60312. var defines = [];
  60313. var options = {
  60314. attributes: [BABYLON.VertexBuffer.PositionKind],
  60315. uniforms: ["world", "viewProjection"],
  60316. needAlphaBlending: true,
  60317. defines: defines
  60318. };
  60319. if (useVertexAlpha === false) {
  60320. options.needAlphaBlending = false;
  60321. }
  60322. if (!useVertexColor) {
  60323. options.uniforms.push("color");
  60324. }
  60325. else {
  60326. options.defines.push("#define VERTEXCOLOR");
  60327. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60328. }
  60329. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60330. return _this;
  60331. }
  60332. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60333. /**
  60334. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60335. * This margin is expressed in world space coordinates, so its value may vary.
  60336. * Default value is 0.1
  60337. * @returns the intersection Threshold value.
  60338. */
  60339. get: function () {
  60340. return this._intersectionThreshold;
  60341. },
  60342. /**
  60343. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60344. * This margin is expressed in world space coordinates, so its value may vary.
  60345. * @param value the new threshold to apply
  60346. */
  60347. set: function (value) {
  60348. if (this._intersectionThreshold === value) {
  60349. return;
  60350. }
  60351. this._intersectionThreshold = value;
  60352. if (this.geometry) {
  60353. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60354. }
  60355. },
  60356. enumerable: true,
  60357. configurable: true
  60358. });
  60359. /**
  60360. * Returns the string "LineMesh"
  60361. */
  60362. LinesMesh.prototype.getClassName = function () {
  60363. return "LinesMesh";
  60364. };
  60365. Object.defineProperty(LinesMesh.prototype, "material", {
  60366. get: function () {
  60367. return this._colorShader;
  60368. },
  60369. set: function (value) {
  60370. // Do nothing
  60371. },
  60372. enumerable: true,
  60373. configurable: true
  60374. });
  60375. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60376. get: function () {
  60377. return false;
  60378. },
  60379. enumerable: true,
  60380. configurable: true
  60381. });
  60382. LinesMesh.prototype.createInstance = function (name) {
  60383. throw new Error("LinesMeshes do not support createInstance.");
  60384. };
  60385. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60386. if (!this._geometry) {
  60387. return this;
  60388. }
  60389. // VBOs
  60390. this._geometry._bind(this._colorShader.getEffect());
  60391. // Color
  60392. if (!this.useVertexColor) {
  60393. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60394. }
  60395. return this;
  60396. };
  60397. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60398. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60399. return this;
  60400. }
  60401. var engine = this.getScene().getEngine();
  60402. // Draw order
  60403. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60404. return this;
  60405. };
  60406. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60407. this._colorShader.dispose();
  60408. _super.prototype.dispose.call(this, doNotRecurse);
  60409. };
  60410. /**
  60411. * Returns a new LineMesh object cloned from the current one.
  60412. */
  60413. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60414. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60415. };
  60416. return LinesMesh;
  60417. }(BABYLON.Mesh));
  60418. BABYLON.LinesMesh = LinesMesh;
  60419. })(BABYLON || (BABYLON = {}));
  60420. //# sourceMappingURL=babylon.linesMesh.js.map
  60421. var BABYLON;
  60422. (function (BABYLON) {
  60423. /**
  60424. * Class containing static functions to help procedurally build meshes
  60425. */
  60426. var MeshBuilder = /** @class */ (function () {
  60427. function MeshBuilder() {
  60428. }
  60429. MeshBuilder.updateSideOrientation = function (orientation) {
  60430. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60431. return BABYLON.Mesh.DOUBLESIDE;
  60432. }
  60433. if (orientation === undefined || orientation === null) {
  60434. return BABYLON.Mesh.FRONTSIDE;
  60435. }
  60436. return orientation;
  60437. };
  60438. /**
  60439. * Creates a box mesh
  60440. * * The parameter `size` sets the size (float) of each box side (default 1)
  60441. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60442. * * 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)
  60443. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60444. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60445. * * 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
  60446. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60447. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60448. * @param name defines the name of the mesh
  60449. * @param options defines the options used to create the mesh
  60450. * @param scene defines the hosting scene
  60451. * @returns the box mesh
  60452. */
  60453. MeshBuilder.CreateBox = function (name, options, scene) {
  60454. if (scene === void 0) { scene = null; }
  60455. var box = new BABYLON.Mesh(name, scene);
  60456. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60457. box._originalBuilderSideOrientation = options.sideOrientation;
  60458. var vertexData = BABYLON.VertexData.CreateBox(options);
  60459. vertexData.applyToMesh(box, options.updatable);
  60460. return box;
  60461. };
  60462. /**
  60463. * Creates a sphere mesh
  60464. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60465. * * 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`)
  60466. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60467. * * 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
  60468. * * 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)
  60469. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60470. * * 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
  60471. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60472. * @param name defines the name of the mesh
  60473. * @param options defines the options used to create the mesh
  60474. * @param scene defines the hosting scene
  60475. * @returns the sphere mesh
  60476. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60477. */
  60478. MeshBuilder.CreateSphere = function (name, options, scene) {
  60479. var sphere = new BABYLON.Mesh(name, scene);
  60480. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60481. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60482. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60483. vertexData.applyToMesh(sphere, options.updatable);
  60484. return sphere;
  60485. };
  60486. /**
  60487. * Creates a plane polygonal mesh. By default, this is a disc
  60488. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60489. * * 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
  60490. * * 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
  60491. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60492. * * 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
  60493. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60494. * @param name defines the name of the mesh
  60495. * @param options defines the options used to create the mesh
  60496. * @param scene defines the hosting scene
  60497. * @returns the plane polygonal mesh
  60498. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60499. */
  60500. MeshBuilder.CreateDisc = function (name, options, scene) {
  60501. if (scene === void 0) { scene = null; }
  60502. var disc = new BABYLON.Mesh(name, scene);
  60503. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60504. disc._originalBuilderSideOrientation = options.sideOrientation;
  60505. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60506. vertexData.applyToMesh(disc, options.updatable);
  60507. return disc;
  60508. };
  60509. /**
  60510. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60511. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60512. * * 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`)
  60513. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60514. * * 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
  60515. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60516. * * 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
  60517. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60518. * @param name defines the name of the mesh
  60519. * @param options defines the options used to create the mesh
  60520. * @param scene defines the hosting scene
  60521. * @returns the icosahedron mesh
  60522. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60523. */
  60524. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60525. var sphere = new BABYLON.Mesh(name, scene);
  60526. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60527. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60528. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60529. vertexData.applyToMesh(sphere, options.updatable);
  60530. return sphere;
  60531. };
  60532. ;
  60533. /**
  60534. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60535. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60536. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60537. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60538. * * 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
  60539. * * 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
  60540. * * 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
  60541. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60542. * * 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
  60543. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60544. * * 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
  60545. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60546. * * 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
  60547. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60548. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60549. * @param name defines the name of the mesh
  60550. * @param options defines the options used to create the mesh
  60551. * @param scene defines the hosting scene
  60552. * @returns the ribbon mesh
  60553. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60554. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60555. */
  60556. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60557. if (scene === void 0) { scene = null; }
  60558. var pathArray = options.pathArray;
  60559. var closeArray = options.closeArray;
  60560. var closePath = options.closePath;
  60561. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60562. var instance = options.instance;
  60563. var updatable = options.updatable;
  60564. if (instance) { // existing ribbon instance update
  60565. // positionFunction : ribbon case
  60566. // only pathArray and sideOrientation parameters are taken into account for positions update
  60567. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60568. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60569. var positionFunction = function (positions) {
  60570. var minlg = pathArray[0].length;
  60571. var i = 0;
  60572. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60573. for (var si = 1; si <= ns; si++) {
  60574. for (var p = 0; p < pathArray.length; p++) {
  60575. var path = pathArray[p];
  60576. var l = path.length;
  60577. minlg = (minlg < l) ? minlg : l;
  60578. var j = 0;
  60579. while (j < minlg) {
  60580. positions[i] = path[j].x;
  60581. positions[i + 1] = path[j].y;
  60582. positions[i + 2] = path[j].z;
  60583. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60584. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60585. }
  60586. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60587. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60588. }
  60589. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60590. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60591. }
  60592. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60593. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60594. }
  60595. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60596. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60597. }
  60598. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60599. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60600. }
  60601. j++;
  60602. i += 3;
  60603. }
  60604. if (instance._closePath) {
  60605. positions[i] = path[0].x;
  60606. positions[i + 1] = path[0].y;
  60607. positions[i + 2] = path[0].z;
  60608. i += 3;
  60609. }
  60610. }
  60611. }
  60612. };
  60613. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60614. positionFunction(positions);
  60615. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60616. instance._boundingInfo.update(instance._worldMatrix);
  60617. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60618. if (options.colors) {
  60619. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60620. for (var c = 0; c < options.colors.length; c++) {
  60621. colors[c * 4] = options.colors[c].r;
  60622. colors[c * 4 + 1] = options.colors[c].g;
  60623. colors[c * 4 + 2] = options.colors[c].b;
  60624. colors[c * 4 + 3] = options.colors[c].a;
  60625. }
  60626. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60627. }
  60628. if (options.uvs) {
  60629. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60630. for (var i = 0; i < options.uvs.length; i++) {
  60631. uvs[i * 2] = options.uvs[i].x;
  60632. uvs[i * 2 + 1] = options.uvs[i].y;
  60633. }
  60634. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60635. }
  60636. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60637. var indices = instance.getIndices();
  60638. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60639. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60640. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60641. if (instance._closePath) {
  60642. var indexFirst = 0;
  60643. var indexLast = 0;
  60644. for (var p = 0; p < pathArray.length; p++) {
  60645. indexFirst = instance._idx[p] * 3;
  60646. if (p + 1 < pathArray.length) {
  60647. indexLast = (instance._idx[p + 1] - 1) * 3;
  60648. }
  60649. else {
  60650. indexLast = normals.length - 3;
  60651. }
  60652. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60653. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60654. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60655. normals[indexLast] = normals[indexFirst];
  60656. normals[indexLast + 1] = normals[indexFirst + 1];
  60657. normals[indexLast + 2] = normals[indexFirst + 2];
  60658. }
  60659. }
  60660. if (!(instance.areNormalsFrozen)) {
  60661. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60662. }
  60663. }
  60664. return instance;
  60665. }
  60666. else { // new ribbon creation
  60667. var ribbon = new BABYLON.Mesh(name, scene);
  60668. ribbon._originalBuilderSideOrientation = sideOrientation;
  60669. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60670. if (closePath) {
  60671. ribbon._idx = vertexData._idx;
  60672. }
  60673. ribbon._closePath = closePath;
  60674. ribbon._closeArray = closeArray;
  60675. vertexData.applyToMesh(ribbon, updatable);
  60676. return ribbon;
  60677. }
  60678. };
  60679. /**
  60680. * Creates a cylinder or a cone mesh
  60681. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60682. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60683. * * 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.
  60684. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60685. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60686. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60687. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60688. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60689. * * 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).
  60690. * * 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
  60691. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60692. * * 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
  60693. * * 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.
  60694. * * If `enclose` is false, a ring surface is one element.
  60695. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60696. * * 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
  60697. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60698. * * 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
  60699. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60700. * @param name defines the name of the mesh
  60701. * @param options defines the options used to create the mesh
  60702. * @param scene defines the hosting scene
  60703. * @returns the cylinder mesh
  60704. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60705. */
  60706. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60707. var cylinder = new BABYLON.Mesh(name, scene);
  60708. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60709. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60710. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60711. vertexData.applyToMesh(cylinder, options.updatable);
  60712. return cylinder;
  60713. };
  60714. /**
  60715. * Creates a torus mesh
  60716. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60717. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60718. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60719. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60720. * * 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
  60721. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60722. * @param name defines the name of the mesh
  60723. * @param options defines the options used to create the mesh
  60724. * @param scene defines the hosting scene
  60725. * @returns the torus mesh
  60726. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60727. */
  60728. MeshBuilder.CreateTorus = function (name, options, scene) {
  60729. var torus = new BABYLON.Mesh(name, scene);
  60730. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60731. torus._originalBuilderSideOrientation = options.sideOrientation;
  60732. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60733. vertexData.applyToMesh(torus, options.updatable);
  60734. return torus;
  60735. };
  60736. /**
  60737. * Creates a torus knot mesh
  60738. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60739. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60740. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60741. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60742. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60743. * * 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
  60744. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60745. * @param name defines the name of the mesh
  60746. * @param options defines the options used to create the mesh
  60747. * @param scene defines the hosting scene
  60748. * @returns the torus knot mesh
  60749. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60750. */
  60751. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60752. var torusKnot = new BABYLON.Mesh(name, scene);
  60753. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60754. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60755. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60756. vertexData.applyToMesh(torusKnot, options.updatable);
  60757. return torusKnot;
  60758. };
  60759. /**
  60760. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60761. * * 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
  60762. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60763. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60764. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60765. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60766. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60767. * * 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
  60768. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60769. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60770. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60771. * @param name defines the name of the new line system
  60772. * @param options defines the options used to create the line system
  60773. * @param scene defines the hosting scene
  60774. * @returns a new line system mesh
  60775. */
  60776. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60777. var instance = options.instance;
  60778. var lines = options.lines;
  60779. var colors = options.colors;
  60780. if (instance) { // lines update
  60781. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60782. var vertexColor;
  60783. var lineColors;
  60784. if (colors) {
  60785. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60786. }
  60787. var i = 0;
  60788. var c = 0;
  60789. for (var l = 0; l < lines.length; l++) {
  60790. var points = lines[l];
  60791. for (var p = 0; p < points.length; p++) {
  60792. positions[i] = points[p].x;
  60793. positions[i + 1] = points[p].y;
  60794. positions[i + 2] = points[p].z;
  60795. if (colors && vertexColor) {
  60796. lineColors = colors[l];
  60797. vertexColor[c] = lineColors[p].r;
  60798. vertexColor[c + 1] = lineColors[p].g;
  60799. vertexColor[c + 2] = lineColors[p].b;
  60800. vertexColor[c + 3] = lineColors[p].a;
  60801. c += 4;
  60802. }
  60803. i += 3;
  60804. }
  60805. }
  60806. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60807. if (colors && vertexColor) {
  60808. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60809. }
  60810. return instance;
  60811. }
  60812. // line system creation
  60813. var useVertexColor = (colors) ? true : false;
  60814. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60815. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60816. vertexData.applyToMesh(lineSystem, options.updatable);
  60817. return lineSystem;
  60818. };
  60819. /**
  60820. * Creates a line mesh
  60821. * 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
  60822. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60823. * * The parameter `points` is an array successive Vector3
  60824. * * 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
  60825. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60826. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60827. * * When updating an instance, remember that only point positions can change, not the number of points
  60828. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60829. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60830. * @param name defines the name of the new line system
  60831. * @param options defines the options used to create the line system
  60832. * @param scene defines the hosting scene
  60833. * @returns a new line mesh
  60834. */
  60835. MeshBuilder.CreateLines = function (name, options, scene) {
  60836. if (scene === void 0) { scene = null; }
  60837. var colors = (options.colors) ? [options.colors] : null;
  60838. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60839. return lines;
  60840. };
  60841. /**
  60842. * Creates a dashed line mesh
  60843. * * 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
  60844. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60845. * * The parameter `points` is an array successive Vector3
  60846. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60847. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60848. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60849. * * 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
  60850. * * When updating an instance, remember that only point positions can change, not the number of points
  60851. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60852. * @param name defines the name of the mesh
  60853. * @param options defines the options used to create the mesh
  60854. * @param scene defines the hosting scene
  60855. * @returns the dashed line mesh
  60856. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60857. */
  60858. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60859. if (scene === void 0) { scene = null; }
  60860. var points = options.points;
  60861. var instance = options.instance;
  60862. var gapSize = options.gapSize || 1;
  60863. var dashSize = options.dashSize || 3;
  60864. if (instance) { // dashed lines update
  60865. var positionFunction = function (positions) {
  60866. var curvect = BABYLON.Vector3.Zero();
  60867. var nbSeg = positions.length / 6;
  60868. var lg = 0;
  60869. var nb = 0;
  60870. var shft = 0;
  60871. var dashshft = 0;
  60872. var curshft = 0;
  60873. var p = 0;
  60874. var i = 0;
  60875. var j = 0;
  60876. for (i = 0; i < points.length - 1; i++) {
  60877. points[i + 1].subtractToRef(points[i], curvect);
  60878. lg += curvect.length();
  60879. }
  60880. shft = lg / nbSeg;
  60881. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60882. for (i = 0; i < points.length - 1; i++) {
  60883. points[i + 1].subtractToRef(points[i], curvect);
  60884. nb = Math.floor(curvect.length() / shft);
  60885. curvect.normalize();
  60886. j = 0;
  60887. while (j < nb && p < positions.length) {
  60888. curshft = shft * j;
  60889. positions[p] = points[i].x + curshft * curvect.x;
  60890. positions[p + 1] = points[i].y + curshft * curvect.y;
  60891. positions[p + 2] = points[i].z + curshft * curvect.z;
  60892. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60893. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60894. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60895. p += 6;
  60896. j++;
  60897. }
  60898. }
  60899. while (p < positions.length) {
  60900. positions[p] = points[i].x;
  60901. positions[p + 1] = points[i].y;
  60902. positions[p + 2] = points[i].z;
  60903. p += 3;
  60904. }
  60905. };
  60906. instance.updateMeshPositions(positionFunction, false);
  60907. return instance;
  60908. }
  60909. // dashed lines creation
  60910. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60911. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60912. vertexData.applyToMesh(dashedLines, options.updatable);
  60913. dashedLines.dashSize = dashSize;
  60914. dashedLines.gapSize = gapSize;
  60915. return dashedLines;
  60916. };
  60917. /**
  60918. * 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.
  60919. * * 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.
  60920. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60921. * * 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.
  60922. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60923. * * 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
  60924. * * 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
  60925. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60926. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60927. * * 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
  60928. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60929. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60930. * @param name defines the name of the mesh
  60931. * @param options defines the options used to create the mesh
  60932. * @param scene defines the hosting scene
  60933. * @returns the extruded shape mesh
  60934. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60935. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60936. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60937. */
  60938. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60939. if (scene === void 0) { scene = null; }
  60940. var path = options.path;
  60941. var shape = options.shape;
  60942. var scale = options.scale || 1;
  60943. var rotation = options.rotation || 0;
  60944. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60945. var updatable = options.updatable;
  60946. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60947. var instance = options.instance || null;
  60948. var invertUV = options.invertUV || false;
  60949. 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);
  60950. };
  60951. /**
  60952. * Creates an custom extruded shape mesh.
  60953. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60954. * * 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.
  60955. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60956. * * 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
  60957. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60958. * * 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
  60959. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60960. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60961. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60962. * * 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
  60963. * * 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
  60964. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60965. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60966. * * 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
  60967. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60968. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60969. * @param name defines the name of the mesh
  60970. * @param options defines the options used to create the mesh
  60971. * @param scene defines the hosting scene
  60972. * @returns the custom extruded shape mesh
  60973. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60974. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60975. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60976. */
  60977. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60978. var path = options.path;
  60979. var shape = options.shape;
  60980. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60981. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60982. var ribbonCloseArray = options.ribbonCloseArray || false;
  60983. var ribbonClosePath = options.ribbonClosePath || false;
  60984. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60985. var updatable = options.updatable;
  60986. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60987. var instance = options.instance;
  60988. var invertUV = options.invertUV || false;
  60989. 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);
  60990. };
  60991. /**
  60992. * Creates lathe mesh.
  60993. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60994. * * 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
  60995. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60996. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60997. * * 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
  60998. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60999. * * 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
  61000. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61001. * * 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
  61002. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61003. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61004. * @param name defines the name of the mesh
  61005. * @param options defines the options used to create the mesh
  61006. * @param scene defines the hosting scene
  61007. * @returns the lathe mesh
  61008. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61009. */
  61010. MeshBuilder.CreateLathe = function (name, options, scene) {
  61011. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61012. var closed = (options.closed === undefined) ? true : options.closed;
  61013. var shape = options.shape;
  61014. var radius = options.radius || 1;
  61015. var tessellation = options.tessellation || 64;
  61016. var updatable = options.updatable;
  61017. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61018. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61019. var pi2 = Math.PI * 2;
  61020. var paths = new Array();
  61021. var invertUV = options.invertUV || false;
  61022. var i = 0;
  61023. var p = 0;
  61024. var step = pi2 / tessellation * arc;
  61025. var rotated;
  61026. var path = new Array();
  61027. for (i = 0; i <= tessellation; i++) {
  61028. var path = [];
  61029. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61030. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61031. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61032. }
  61033. for (p = 0; p < shape.length; p++) {
  61034. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61035. path.push(rotated);
  61036. }
  61037. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61038. 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));
  61039. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61040. }
  61041. paths.push(path);
  61042. }
  61043. // lathe ribbon
  61044. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61045. return lathe;
  61046. };
  61047. /**
  61048. * Creates a plane mesh
  61049. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61050. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61051. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61052. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61053. * * 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
  61054. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61055. * @param name defines the name of the mesh
  61056. * @param options defines the options used to create the mesh
  61057. * @param scene defines the hosting scene
  61058. * @returns the plane mesh
  61059. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61060. */
  61061. MeshBuilder.CreatePlane = function (name, options, scene) {
  61062. var plane = new BABYLON.Mesh(name, scene);
  61063. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61064. plane._originalBuilderSideOrientation = options.sideOrientation;
  61065. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61066. vertexData.applyToMesh(plane, options.updatable);
  61067. if (options.sourcePlane) {
  61068. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61069. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61070. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61071. plane.rotate(vectorProduct, product);
  61072. }
  61073. return plane;
  61074. };
  61075. /**
  61076. * Creates a ground mesh
  61077. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61078. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61079. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61080. * @param name defines the name of the mesh
  61081. * @param options defines the options used to create the mesh
  61082. * @param scene defines the hosting scene
  61083. * @returns the ground mesh
  61084. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61085. */
  61086. MeshBuilder.CreateGround = function (name, options, scene) {
  61087. var ground = new BABYLON.GroundMesh(name, scene);
  61088. ground._setReady(false);
  61089. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61090. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61091. ground._width = options.width || 1;
  61092. ground._height = options.height || 1;
  61093. ground._maxX = ground._width / 2;
  61094. ground._maxZ = ground._height / 2;
  61095. ground._minX = -ground._maxX;
  61096. ground._minZ = -ground._maxZ;
  61097. var vertexData = BABYLON.VertexData.CreateGround(options);
  61098. vertexData.applyToMesh(ground, options.updatable);
  61099. ground._setReady(true);
  61100. return ground;
  61101. };
  61102. /**
  61103. * Creates a tiled ground mesh
  61104. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61105. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61106. * * 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
  61107. * * 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
  61108. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61109. * @param name defines the name of the mesh
  61110. * @param options defines the options used to create the mesh
  61111. * @param scene defines the hosting scene
  61112. * @returns the tiled ground mesh
  61113. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61114. */
  61115. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61116. var tiledGround = new BABYLON.Mesh(name, scene);
  61117. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61118. vertexData.applyToMesh(tiledGround, options.updatable);
  61119. return tiledGround;
  61120. };
  61121. /**
  61122. * Creates a ground mesh from a height map
  61123. * * The parameter `url` sets the URL of the height map image resource.
  61124. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61125. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61126. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61127. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61128. * * 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.
  61129. * * 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).
  61130. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61131. * @param name defines the name of the mesh
  61132. * @param url defines the url to the height map
  61133. * @param options defines the options used to create the mesh
  61134. * @param scene defines the hosting scene
  61135. * @returns the ground mesh
  61136. * @see http://doc.babylonjs.com/babylon101/height_map
  61137. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61138. */
  61139. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61140. var width = options.width || 10.0;
  61141. var height = options.height || 10.0;
  61142. var subdivisions = options.subdivisions || 1 | 0;
  61143. var minHeight = options.minHeight || 0.0;
  61144. var maxHeight = options.maxHeight || 1.0;
  61145. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61146. var updatable = options.updatable;
  61147. var onReady = options.onReady;
  61148. var ground = new BABYLON.GroundMesh(name, scene);
  61149. ground._subdivisionsX = subdivisions;
  61150. ground._subdivisionsY = subdivisions;
  61151. ground._width = width;
  61152. ground._height = height;
  61153. ground._maxX = ground._width / 2.0;
  61154. ground._maxZ = ground._height / 2.0;
  61155. ground._minX = -ground._maxX;
  61156. ground._minZ = -ground._maxZ;
  61157. ground._setReady(false);
  61158. var onload = function (img) {
  61159. // Getting height map data
  61160. var canvas = document.createElement("canvas");
  61161. var context = canvas.getContext("2d");
  61162. if (!context) {
  61163. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61164. }
  61165. if (scene.isDisposed) {
  61166. return;
  61167. }
  61168. var bufferWidth = img.width;
  61169. var bufferHeight = img.height;
  61170. canvas.width = bufferWidth;
  61171. canvas.height = bufferHeight;
  61172. context.drawImage(img, 0, 0);
  61173. // Create VertexData from map data
  61174. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61175. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61176. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61177. width: width, height: height,
  61178. subdivisions: subdivisions,
  61179. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61180. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61181. });
  61182. vertexData.applyToMesh(ground, updatable);
  61183. //execute ready callback, if set
  61184. if (onReady) {
  61185. onReady(ground);
  61186. }
  61187. ground._setReady(true);
  61188. };
  61189. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61190. return ground;
  61191. };
  61192. /**
  61193. * Creates a polygon mesh
  61194. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61195. * * 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
  61196. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61197. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61198. * * 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)
  61199. * * Remember you can only change the shape positions, not their number when updating a polygon
  61200. * @param name defines the name of the mesh
  61201. * @param options defines the options used to create the mesh
  61202. * @param scene defines the hosting scene
  61203. * @returns the polygon mesh
  61204. */
  61205. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61206. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61207. var shape = options.shape;
  61208. var holes = options.holes || [];
  61209. var depth = options.depth || 0;
  61210. var contours = [];
  61211. var hole = [];
  61212. for (var i = 0; i < shape.length; i++) {
  61213. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61214. }
  61215. var epsilon = 0.00000001;
  61216. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61217. contours.pop();
  61218. }
  61219. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61220. for (var hNb = 0; hNb < holes.length; hNb++) {
  61221. hole = [];
  61222. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61223. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61224. }
  61225. polygonTriangulation.addHole(hole);
  61226. }
  61227. var polygon = polygonTriangulation.build(options.updatable, depth);
  61228. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61229. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61230. vertexData.applyToMesh(polygon, options.updatable);
  61231. return polygon;
  61232. };
  61233. ;
  61234. /**
  61235. * Creates an extruded polygon mesh, with depth in the Y direction.
  61236. * * 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)
  61237. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61238. * @param name defines the name of the mesh
  61239. * @param options defines the options used to create the mesh
  61240. * @param scene defines the hosting scene
  61241. * @returns the polygon mesh
  61242. */
  61243. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61244. return MeshBuilder.CreatePolygon(name, options, scene);
  61245. };
  61246. ;
  61247. /**
  61248. * Creates a tube mesh.
  61249. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61250. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61251. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61252. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61253. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61254. * * 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)
  61255. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61256. * * 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
  61257. * * 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
  61258. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61259. * * 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
  61260. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61261. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61262. * @param name defines the name of the mesh
  61263. * @param options defines the options used to create the mesh
  61264. * @param scene defines the hosting scene
  61265. * @returns the tube mesh
  61266. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61267. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61268. */
  61269. MeshBuilder.CreateTube = function (name, options, scene) {
  61270. var path = options.path;
  61271. var instance = options.instance;
  61272. var radius = 1.0;
  61273. if (instance) {
  61274. radius = instance.radius;
  61275. }
  61276. if (options.radius !== undefined) {
  61277. radius = options.radius;
  61278. }
  61279. ;
  61280. var tessellation = options.tessellation || 64 | 0;
  61281. var radiusFunction = options.radiusFunction || null;
  61282. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61283. var invertUV = options.invertUV || false;
  61284. var updatable = options.updatable;
  61285. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61286. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61287. // tube geometry
  61288. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61289. var tangents = path3D.getTangents();
  61290. var normals = path3D.getNormals();
  61291. var distances = path3D.getDistances();
  61292. var pi2 = Math.PI * 2;
  61293. var step = pi2 / tessellation * arc;
  61294. var returnRadius = function () { return radius; };
  61295. var radiusFunctionFinal = radiusFunction || returnRadius;
  61296. var circlePath;
  61297. var rad;
  61298. var normal;
  61299. var rotated;
  61300. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61301. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61302. for (var i = 0; i < path.length; i++) {
  61303. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61304. circlePath = Array(); // current circle array
  61305. normal = normals[i]; // current normal
  61306. for (var t = 0; t < tessellation; t++) {
  61307. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61308. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61309. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61310. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61311. circlePath[t] = rotated;
  61312. }
  61313. circlePaths[index] = circlePath;
  61314. index++;
  61315. }
  61316. // cap
  61317. var capPath = function (nbPoints, pathIndex) {
  61318. var pointCap = Array();
  61319. for (var i = 0; i < nbPoints; i++) {
  61320. pointCap.push(path[pathIndex]);
  61321. }
  61322. return pointCap;
  61323. };
  61324. switch (cap) {
  61325. case BABYLON.Mesh.NO_CAP:
  61326. break;
  61327. case BABYLON.Mesh.CAP_START:
  61328. circlePaths[0] = capPath(tessellation, 0);
  61329. circlePaths[1] = circlePaths[2].slice(0);
  61330. break;
  61331. case BABYLON.Mesh.CAP_END:
  61332. circlePaths[index] = circlePaths[index - 1].slice(0);
  61333. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61334. break;
  61335. case BABYLON.Mesh.CAP_ALL:
  61336. circlePaths[0] = capPath(tessellation, 0);
  61337. circlePaths[1] = circlePaths[2].slice(0);
  61338. circlePaths[index] = circlePaths[index - 1].slice(0);
  61339. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61340. break;
  61341. default:
  61342. break;
  61343. }
  61344. return circlePaths;
  61345. };
  61346. var path3D;
  61347. var pathArray;
  61348. if (instance) { // tube update
  61349. var arc = options.arc || instance.arc;
  61350. path3D = (instance.path3D).update(path);
  61351. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61352. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61353. instance.path3D = path3D;
  61354. instance.pathArray = pathArray;
  61355. instance.arc = arc;
  61356. instance.radius = radius;
  61357. return instance;
  61358. }
  61359. // tube creation
  61360. path3D = new BABYLON.Path3D(path);
  61361. var newPathArray = new Array();
  61362. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61363. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61364. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61365. tube.pathArray = pathArray;
  61366. tube.path3D = path3D;
  61367. tube.tessellation = tessellation;
  61368. tube.cap = cap;
  61369. tube.arc = options.arc;
  61370. tube.radius = radius;
  61371. return tube;
  61372. };
  61373. /**
  61374. * Creates a polyhedron mesh
  61375. * * 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
  61376. * * The parameter `size` (positive float, default 1) sets the polygon size
  61377. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61378. * * 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`
  61379. * * 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
  61380. * * 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)`)
  61381. * * 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
  61382. * * 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
  61383. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61384. * * 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
  61385. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61386. * @param name defines the name of the mesh
  61387. * @param options defines the options used to create the mesh
  61388. * @param scene defines the hosting scene
  61389. * @returns the polyhedron mesh
  61390. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61391. */
  61392. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61393. var polyhedron = new BABYLON.Mesh(name, scene);
  61394. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61395. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61396. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61397. vertexData.applyToMesh(polyhedron, options.updatable);
  61398. return polyhedron;
  61399. };
  61400. /**
  61401. * Creates a decal mesh.
  61402. * 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
  61403. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61404. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61405. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61406. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61407. * @param name defines the name of the mesh
  61408. * @param sourceMesh defines the mesh where the decal must be applied
  61409. * @param options defines the options used to create the mesh
  61410. * @param scene defines the hosting scene
  61411. * @returns the decal mesh
  61412. * @see http://doc.babylonjs.com/how_to/decals
  61413. */
  61414. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61415. var indices = sourceMesh.getIndices();
  61416. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61417. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61418. var position = options.position || BABYLON.Vector3.Zero();
  61419. var normal = options.normal || BABYLON.Vector3.Up();
  61420. var size = options.size || BABYLON.Vector3.One();
  61421. var angle = options.angle || 0;
  61422. // Getting correct rotation
  61423. if (!normal) {
  61424. var target = new BABYLON.Vector3(0, 0, 1);
  61425. var camera = sourceMesh.getScene().activeCamera;
  61426. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61427. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61428. }
  61429. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61430. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61431. var pitch = Math.atan2(normal.y, len);
  61432. // Matrix
  61433. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61434. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61435. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61436. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61437. var vertexData = new BABYLON.VertexData();
  61438. vertexData.indices = [];
  61439. vertexData.positions = [];
  61440. vertexData.normals = [];
  61441. vertexData.uvs = [];
  61442. var currentVertexDataIndex = 0;
  61443. var extractDecalVector3 = function (indexId) {
  61444. var result = new BABYLON.PositionNormalVertex();
  61445. if (!indices || !positions || !normals) {
  61446. return result;
  61447. }
  61448. var vertexId = indices[indexId];
  61449. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61450. // Send vector to decal local world
  61451. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61452. // Get normal
  61453. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61454. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61455. return result;
  61456. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61457. var clip = function (vertices, axis) {
  61458. if (vertices.length === 0) {
  61459. return vertices;
  61460. }
  61461. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61462. var clipVertices = function (v0, v1) {
  61463. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61464. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61465. };
  61466. var result = new Array();
  61467. for (var index = 0; index < vertices.length; index += 3) {
  61468. var v1Out;
  61469. var v2Out;
  61470. var v3Out;
  61471. var total = 0;
  61472. var nV1 = null;
  61473. var nV2 = null;
  61474. var nV3 = null;
  61475. var nV4 = null;
  61476. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61477. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61478. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61479. v1Out = d1 > 0;
  61480. v2Out = d2 > 0;
  61481. v3Out = d3 > 0;
  61482. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61483. switch (total) {
  61484. case 0:
  61485. result.push(vertices[index]);
  61486. result.push(vertices[index + 1]);
  61487. result.push(vertices[index + 2]);
  61488. break;
  61489. case 1:
  61490. if (v1Out) {
  61491. nV1 = vertices[index + 1];
  61492. nV2 = vertices[index + 2];
  61493. nV3 = clipVertices(vertices[index], nV1);
  61494. nV4 = clipVertices(vertices[index], nV2);
  61495. }
  61496. if (v2Out) {
  61497. nV1 = vertices[index];
  61498. nV2 = vertices[index + 2];
  61499. nV3 = clipVertices(vertices[index + 1], nV1);
  61500. nV4 = clipVertices(vertices[index + 1], nV2);
  61501. result.push(nV3);
  61502. result.push(nV2.clone());
  61503. result.push(nV1.clone());
  61504. result.push(nV2.clone());
  61505. result.push(nV3.clone());
  61506. result.push(nV4);
  61507. break;
  61508. }
  61509. if (v3Out) {
  61510. nV1 = vertices[index];
  61511. nV2 = vertices[index + 1];
  61512. nV3 = clipVertices(vertices[index + 2], nV1);
  61513. nV4 = clipVertices(vertices[index + 2], nV2);
  61514. }
  61515. if (nV1 && nV2 && nV3 && nV4) {
  61516. result.push(nV1.clone());
  61517. result.push(nV2.clone());
  61518. result.push(nV3);
  61519. result.push(nV4);
  61520. result.push(nV3.clone());
  61521. result.push(nV2.clone());
  61522. }
  61523. break;
  61524. case 2:
  61525. if (!v1Out) {
  61526. nV1 = vertices[index].clone();
  61527. nV2 = clipVertices(nV1, vertices[index + 1]);
  61528. nV3 = clipVertices(nV1, vertices[index + 2]);
  61529. result.push(nV1);
  61530. result.push(nV2);
  61531. result.push(nV3);
  61532. }
  61533. if (!v2Out) {
  61534. nV1 = vertices[index + 1].clone();
  61535. nV2 = clipVertices(nV1, vertices[index + 2]);
  61536. nV3 = clipVertices(nV1, vertices[index]);
  61537. result.push(nV1);
  61538. result.push(nV2);
  61539. result.push(nV3);
  61540. }
  61541. if (!v3Out) {
  61542. nV1 = vertices[index + 2].clone();
  61543. nV2 = clipVertices(nV1, vertices[index]);
  61544. nV3 = clipVertices(nV1, vertices[index + 1]);
  61545. result.push(nV1);
  61546. result.push(nV2);
  61547. result.push(nV3);
  61548. }
  61549. break;
  61550. case 3:
  61551. break;
  61552. }
  61553. }
  61554. return result;
  61555. };
  61556. for (var index = 0; index < indices.length; index += 3) {
  61557. var faceVertices = new Array();
  61558. faceVertices.push(extractDecalVector3(index));
  61559. faceVertices.push(extractDecalVector3(index + 1));
  61560. faceVertices.push(extractDecalVector3(index + 2));
  61561. // Clip
  61562. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61563. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61564. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61565. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61566. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61567. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61568. if (faceVertices.length === 0) {
  61569. continue;
  61570. }
  61571. // Add UVs and get back to world
  61572. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61573. var vertex = faceVertices[vIndex];
  61574. //TODO check for Int32Array | Uint32Array | Uint16Array
  61575. vertexData.indices.push(currentVertexDataIndex);
  61576. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61577. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61578. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61579. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61580. currentVertexDataIndex++;
  61581. }
  61582. }
  61583. // Return mesh
  61584. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61585. vertexData.applyToMesh(decal);
  61586. decal.position = position.clone();
  61587. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61588. return decal;
  61589. };
  61590. // Privates
  61591. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61592. // extrusion geometry
  61593. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61594. var tangents = path3D.getTangents();
  61595. var normals = path3D.getNormals();
  61596. var binormals = path3D.getBinormals();
  61597. var distances = path3D.getDistances();
  61598. var angle = 0;
  61599. var returnScale = function () { return scale !== null ? scale : 1; };
  61600. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61601. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61602. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61603. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61604. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61605. for (var i = 0; i < curve.length; i++) {
  61606. var shapePath = new Array();
  61607. var angleStep = rotate(i, distances[i]);
  61608. var scaleRatio = scl(i, distances[i]);
  61609. for (var p = 0; p < shape.length; p++) {
  61610. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61611. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61612. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61613. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61614. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61615. shapePath[p] = rotated;
  61616. }
  61617. shapePaths[index] = shapePath;
  61618. angle += angleStep;
  61619. index++;
  61620. }
  61621. // cap
  61622. var capPath = function (shapePath) {
  61623. var pointCap = Array();
  61624. var barycenter = BABYLON.Vector3.Zero();
  61625. var i;
  61626. for (i = 0; i < shapePath.length; i++) {
  61627. barycenter.addInPlace(shapePath[i]);
  61628. }
  61629. barycenter.scaleInPlace(1.0 / shapePath.length);
  61630. for (i = 0; i < shapePath.length; i++) {
  61631. pointCap.push(barycenter);
  61632. }
  61633. return pointCap;
  61634. };
  61635. switch (cap) {
  61636. case BABYLON.Mesh.NO_CAP:
  61637. break;
  61638. case BABYLON.Mesh.CAP_START:
  61639. shapePaths[0] = capPath(shapePaths[2]);
  61640. shapePaths[1] = shapePaths[2];
  61641. break;
  61642. case BABYLON.Mesh.CAP_END:
  61643. shapePaths[index] = shapePaths[index - 1];
  61644. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61645. break;
  61646. case BABYLON.Mesh.CAP_ALL:
  61647. shapePaths[0] = capPath(shapePaths[2]);
  61648. shapePaths[1] = shapePaths[2];
  61649. shapePaths[index] = shapePaths[index - 1];
  61650. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61651. break;
  61652. default:
  61653. break;
  61654. }
  61655. return shapePaths;
  61656. };
  61657. var path3D;
  61658. var pathArray;
  61659. if (instance) { // instance update
  61660. path3D = (instance.path3D).update(curve);
  61661. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61662. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61663. return instance;
  61664. }
  61665. // extruded shape creation
  61666. path3D = new BABYLON.Path3D(curve);
  61667. var newShapePaths = new Array();
  61668. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61669. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61670. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61671. extrudedGeneric.pathArray = pathArray;
  61672. extrudedGeneric.path3D = path3D;
  61673. extrudedGeneric.cap = cap;
  61674. return extrudedGeneric;
  61675. };
  61676. return MeshBuilder;
  61677. }());
  61678. BABYLON.MeshBuilder = MeshBuilder;
  61679. })(BABYLON || (BABYLON = {}));
  61680. //# sourceMappingURL=babylon.meshBuilder.js.map
  61681. var BABYLON;
  61682. (function (BABYLON) {
  61683. /**
  61684. * Draco compression (https://google.github.io/draco/)
  61685. *
  61686. * This class wraps the Draco module.
  61687. *
  61688. * **Encoder**
  61689. *
  61690. * The encoder is not currently implemented.
  61691. *
  61692. * **Decoder**
  61693. *
  61694. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61695. *
  61696. * To update the configuration, use the following code:
  61697. * ```javascript
  61698. * BABYLON.DracoCompression.Configuration = {
  61699. * decoder: {
  61700. * wasmUrl: "<url to the WebAssembly library>",
  61701. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61702. * fallbackUrl: "<url to the fallback JavaScript library>",
  61703. * }
  61704. * };
  61705. * ```
  61706. *
  61707. * 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.
  61708. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61709. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61710. *
  61711. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61712. * ```javascript
  61713. * var dracoCompression = new BABYLON.DracoCompression();
  61714. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61715. * [BABYLON.VertexBuffer.PositionKind]: 0
  61716. * });
  61717. * ```
  61718. *
  61719. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61720. */
  61721. var DracoCompression = /** @class */ (function () {
  61722. /**
  61723. * Constructor
  61724. */
  61725. function DracoCompression() {
  61726. }
  61727. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61728. /**
  61729. * Returns true if the decoder is available.
  61730. */
  61731. get: function () {
  61732. if (typeof DracoDecoderModule !== "undefined") {
  61733. return true;
  61734. }
  61735. var decoder = DracoCompression.Configuration.decoder;
  61736. if (decoder) {
  61737. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61738. return true;
  61739. }
  61740. if (decoder.fallbackUrl) {
  61741. return true;
  61742. }
  61743. }
  61744. return false;
  61745. },
  61746. enumerable: true,
  61747. configurable: true
  61748. });
  61749. /**
  61750. * Stop all async operations and release resources.
  61751. */
  61752. DracoCompression.prototype.dispose = function () {
  61753. };
  61754. /**
  61755. * Decode Draco compressed mesh data to vertex data.
  61756. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61757. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61758. * @returns A promise that resolves with the decoded vertex data
  61759. */
  61760. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61761. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61762. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61763. var module = wrappedModule.module;
  61764. var vertexData = new BABYLON.VertexData();
  61765. var buffer = new module.DecoderBuffer();
  61766. buffer.Init(dataView, dataView.byteLength);
  61767. var decoder = new module.Decoder();
  61768. var geometry;
  61769. var status;
  61770. try {
  61771. var type = decoder.GetEncodedGeometryType(buffer);
  61772. switch (type) {
  61773. case module.TRIANGULAR_MESH:
  61774. geometry = new module.Mesh();
  61775. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61776. break;
  61777. case module.POINT_CLOUD:
  61778. geometry = new module.PointCloud();
  61779. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61780. break;
  61781. default:
  61782. throw new Error("Invalid geometry type " + type);
  61783. }
  61784. if (!status.ok() || !geometry.ptr) {
  61785. throw new Error(status.error_msg());
  61786. }
  61787. var numPoints = geometry.num_points();
  61788. if (type === module.TRIANGULAR_MESH) {
  61789. var numFaces = geometry.num_faces();
  61790. var faceIndices = new module.DracoInt32Array();
  61791. try {
  61792. var indices = new Uint32Array(numFaces * 3);
  61793. for (var i = 0; i < numFaces; i++) {
  61794. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61795. var offset = i * 3;
  61796. indices[offset + 0] = faceIndices.GetValue(0);
  61797. indices[offset + 1] = faceIndices.GetValue(1);
  61798. indices[offset + 2] = faceIndices.GetValue(2);
  61799. }
  61800. vertexData.indices = indices;
  61801. }
  61802. finally {
  61803. module.destroy(faceIndices);
  61804. }
  61805. }
  61806. for (var kind in attributes) {
  61807. var uniqueId = attributes[kind];
  61808. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61809. var dracoData = new module.DracoFloat32Array();
  61810. try {
  61811. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61812. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61813. for (var i = 0; i < babylonData.length; i++) {
  61814. babylonData[i] = dracoData.GetValue(i);
  61815. }
  61816. vertexData.set(babylonData, kind);
  61817. }
  61818. finally {
  61819. module.destroy(dracoData);
  61820. }
  61821. }
  61822. }
  61823. finally {
  61824. if (geometry) {
  61825. module.destroy(geometry);
  61826. }
  61827. module.destroy(decoder);
  61828. module.destroy(buffer);
  61829. }
  61830. return vertexData;
  61831. });
  61832. };
  61833. DracoCompression._GetDecoderModule = function () {
  61834. if (!DracoCompression._DecoderModulePromise) {
  61835. var promise = null;
  61836. var config_1 = {};
  61837. if (typeof DracoDecoderModule !== "undefined") {
  61838. promise = Promise.resolve();
  61839. }
  61840. else {
  61841. var decoder = DracoCompression.Configuration.decoder;
  61842. if (decoder) {
  61843. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61844. promise = Promise.all([
  61845. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61846. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61847. config_1.wasmBinary = data;
  61848. })
  61849. ]);
  61850. }
  61851. else if (decoder.fallbackUrl) {
  61852. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61853. }
  61854. }
  61855. }
  61856. if (!promise) {
  61857. throw new Error("Draco decoder module is not available");
  61858. }
  61859. DracoCompression._DecoderModulePromise = promise.then(function () {
  61860. return new Promise(function (resolve) {
  61861. config_1.onModuleLoaded = function (decoderModule) {
  61862. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61863. resolve({ module: decoderModule });
  61864. };
  61865. DracoDecoderModule(config_1);
  61866. });
  61867. });
  61868. }
  61869. return DracoCompression._DecoderModulePromise;
  61870. };
  61871. DracoCompression._LoadScriptAsync = function (url) {
  61872. return new Promise(function (resolve, reject) {
  61873. BABYLON.Tools.LoadScript(url, function () {
  61874. resolve();
  61875. }, function (message) {
  61876. reject(new Error(message));
  61877. });
  61878. });
  61879. };
  61880. DracoCompression._LoadFileAsync = function (url) {
  61881. return new Promise(function (resolve, reject) {
  61882. BABYLON.Tools.LoadFile(url, function (data) {
  61883. resolve(data);
  61884. }, undefined, undefined, true, function (request, exception) {
  61885. reject(exception);
  61886. });
  61887. });
  61888. };
  61889. /**
  61890. * The configuration. Defaults to the following urls:
  61891. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61892. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61893. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61894. */
  61895. DracoCompression.Configuration = {
  61896. decoder: {
  61897. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61898. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61899. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61900. }
  61901. };
  61902. return DracoCompression;
  61903. }());
  61904. BABYLON.DracoCompression = DracoCompression;
  61905. })(BABYLON || (BABYLON = {}));
  61906. //# sourceMappingURL=babylon.dracoCompression.js.map
  61907. var BABYLON;
  61908. (function (BABYLON) {
  61909. var AudioEngine = /** @class */ (function () {
  61910. function AudioEngine() {
  61911. this._audioContext = null;
  61912. this._audioContextInitialized = false;
  61913. this.canUseWebAudio = false;
  61914. this.WarnedWebAudioUnsupported = false;
  61915. this.unlocked = false;
  61916. this.isMP3supported = false;
  61917. this.isOGGsupported = false;
  61918. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61919. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61920. this.canUseWebAudio = true;
  61921. }
  61922. var audioElem = document.createElement('audio');
  61923. try {
  61924. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61925. this.isMP3supported = true;
  61926. }
  61927. }
  61928. catch (e) {
  61929. // protect error during capability check.
  61930. }
  61931. try {
  61932. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61933. this.isOGGsupported = true;
  61934. }
  61935. }
  61936. catch (e) {
  61937. // protect error during capability check.
  61938. }
  61939. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61940. this._unlockiOSaudio();
  61941. }
  61942. else {
  61943. this.unlocked = true;
  61944. }
  61945. }
  61946. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61947. get: function () {
  61948. if (!this._audioContextInitialized) {
  61949. this._initializeAudioContext();
  61950. }
  61951. return this._audioContext;
  61952. },
  61953. enumerable: true,
  61954. configurable: true
  61955. });
  61956. AudioEngine.prototype._unlockiOSaudio = function () {
  61957. var _this = this;
  61958. var unlockaudio = function () {
  61959. if (!_this.audioContext) {
  61960. return;
  61961. }
  61962. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61963. var source = _this.audioContext.createBufferSource();
  61964. source.buffer = buffer;
  61965. source.connect(_this.audioContext.destination);
  61966. source.start(0);
  61967. setTimeout(function () {
  61968. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61969. _this.unlocked = true;
  61970. window.removeEventListener('touchend', unlockaudio, false);
  61971. if (_this.onAudioUnlocked) {
  61972. _this.onAudioUnlocked();
  61973. }
  61974. }
  61975. }, 0);
  61976. };
  61977. window.addEventListener('touchend', unlockaudio, false);
  61978. };
  61979. AudioEngine.prototype._initializeAudioContext = function () {
  61980. try {
  61981. if (this.canUseWebAudio) {
  61982. this._audioContext = new AudioContext();
  61983. // create a global volume gain node
  61984. this.masterGain = this._audioContext.createGain();
  61985. this.masterGain.gain.value = 1;
  61986. this.masterGain.connect(this._audioContext.destination);
  61987. this._audioContextInitialized = true;
  61988. }
  61989. }
  61990. catch (e) {
  61991. this.canUseWebAudio = false;
  61992. BABYLON.Tools.Error("Web Audio: " + e.message);
  61993. }
  61994. };
  61995. AudioEngine.prototype.dispose = function () {
  61996. if (this.canUseWebAudio && this._audioContextInitialized) {
  61997. if (this._connectedAnalyser && this._audioContext) {
  61998. this._connectedAnalyser.stopDebugCanvas();
  61999. this._connectedAnalyser.dispose();
  62000. this.masterGain.disconnect();
  62001. this.masterGain.connect(this._audioContext.destination);
  62002. this._connectedAnalyser = null;
  62003. }
  62004. this.masterGain.gain.value = 1;
  62005. }
  62006. this.WarnedWebAudioUnsupported = false;
  62007. };
  62008. AudioEngine.prototype.getGlobalVolume = function () {
  62009. if (this.canUseWebAudio && this._audioContextInitialized) {
  62010. return this.masterGain.gain.value;
  62011. }
  62012. else {
  62013. return -1;
  62014. }
  62015. };
  62016. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62017. if (this.canUseWebAudio && this._audioContextInitialized) {
  62018. this.masterGain.gain.value = newVolume;
  62019. }
  62020. };
  62021. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62022. if (this._connectedAnalyser) {
  62023. this._connectedAnalyser.stopDebugCanvas();
  62024. }
  62025. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62026. this._connectedAnalyser = analyser;
  62027. this.masterGain.disconnect();
  62028. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62029. }
  62030. };
  62031. return AudioEngine;
  62032. }());
  62033. BABYLON.AudioEngine = AudioEngine;
  62034. })(BABYLON || (BABYLON = {}));
  62035. //# sourceMappingURL=babylon.audioEngine.js.map
  62036. var BABYLON;
  62037. (function (BABYLON) {
  62038. var Sound = /** @class */ (function () {
  62039. /**
  62040. * Create a sound and attach it to a scene
  62041. * @param name Name of your sound
  62042. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62043. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62044. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62045. */
  62046. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62047. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62048. var _this = this;
  62049. this.autoplay = false;
  62050. this.loop = false;
  62051. this.useCustomAttenuation = false;
  62052. this.spatialSound = false;
  62053. this.refDistance = 1;
  62054. this.rolloffFactor = 1;
  62055. this.maxDistance = 100;
  62056. this.distanceModel = "linear";
  62057. this._panningModel = "equalpower";
  62058. this._playbackRate = 1;
  62059. this._streaming = false;
  62060. this._startTime = 0;
  62061. this._startOffset = 0;
  62062. this._position = BABYLON.Vector3.Zero();
  62063. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62064. this._volume = 1;
  62065. this._isReadyToPlay = false;
  62066. this.isPlaying = false;
  62067. this.isPaused = false;
  62068. this._isDirectional = false;
  62069. // Used if you'd like to create a directional sound.
  62070. // If not set, the sound will be omnidirectional
  62071. this._coneInnerAngle = 360;
  62072. this._coneOuterAngle = 360;
  62073. this._coneOuterGain = 0;
  62074. this._isOutputConnected = false;
  62075. this._urlType = "Unknown";
  62076. this.name = name;
  62077. this._scene = scene;
  62078. this._readyToPlayCallback = readyToPlayCallback;
  62079. // Default custom attenuation function is a linear attenuation
  62080. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62081. if (currentDistance < maxDistance) {
  62082. return currentVolume * (1 - currentDistance / maxDistance);
  62083. }
  62084. else {
  62085. return 0;
  62086. }
  62087. };
  62088. if (options) {
  62089. this.autoplay = options.autoplay || false;
  62090. this.loop = options.loop || false;
  62091. // if volume === 0, we need another way to check this option
  62092. if (options.volume !== undefined) {
  62093. this._volume = options.volume;
  62094. }
  62095. this.spatialSound = options.spatialSound || false;
  62096. this.maxDistance = options.maxDistance || 100;
  62097. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62098. this.rolloffFactor = options.rolloffFactor || 1;
  62099. this.refDistance = options.refDistance || 1;
  62100. this.distanceModel = options.distanceModel || "linear";
  62101. this._playbackRate = options.playbackRate || 1;
  62102. this._streaming = options.streaming || false;
  62103. }
  62104. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62105. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62106. this._soundGain.gain.value = this._volume;
  62107. this._inputAudioNode = this._soundGain;
  62108. this._ouputAudioNode = this._soundGain;
  62109. if (this.spatialSound) {
  62110. this._createSpatialParameters();
  62111. }
  62112. this._scene.mainSoundTrack.AddSound(this);
  62113. var validParameter = true;
  62114. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62115. if (urlOrArrayBuffer) {
  62116. try {
  62117. if (typeof (urlOrArrayBuffer) === "string") {
  62118. this._urlType = "String";
  62119. }
  62120. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62121. this._urlType = "ArrayBuffer";
  62122. }
  62123. else if (urlOrArrayBuffer instanceof MediaStream) {
  62124. this._urlType = "MediaStream";
  62125. }
  62126. else if (Array.isArray(urlOrArrayBuffer)) {
  62127. this._urlType = "Array";
  62128. }
  62129. var urls = [];
  62130. var codecSupportedFound = false;
  62131. switch (this._urlType) {
  62132. case "MediaStream":
  62133. this._streaming = true;
  62134. this._isReadyToPlay = true;
  62135. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62136. if (this.autoplay) {
  62137. this.play();
  62138. }
  62139. if (this._readyToPlayCallback) {
  62140. this._readyToPlayCallback();
  62141. }
  62142. break;
  62143. case "ArrayBuffer":
  62144. if (urlOrArrayBuffer.byteLength > 0) {
  62145. codecSupportedFound = true;
  62146. this._soundLoaded(urlOrArrayBuffer);
  62147. }
  62148. break;
  62149. case "String":
  62150. urls.push(urlOrArrayBuffer);
  62151. case "Array":
  62152. if (urls.length === 0)
  62153. urls = urlOrArrayBuffer;
  62154. // If we found a supported format, we load it immediately and stop the loop
  62155. for (var i = 0; i < urls.length; i++) {
  62156. var url = urls[i];
  62157. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62158. codecSupportedFound = true;
  62159. }
  62160. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62161. codecSupportedFound = true;
  62162. }
  62163. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62164. codecSupportedFound = true;
  62165. }
  62166. if (url.indexOf("blob:") !== -1) {
  62167. codecSupportedFound = true;
  62168. }
  62169. if (codecSupportedFound) {
  62170. // Loading sound using XHR2
  62171. if (!this._streaming) {
  62172. this._scene._loadFile(url, function (data) {
  62173. _this._soundLoaded(data);
  62174. }, undefined, true, true, function (exception) {
  62175. if (exception) {
  62176. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62177. }
  62178. BABYLON.Tools.Error("Sound creation aborted.");
  62179. _this._scene.mainSoundTrack.RemoveSound(_this);
  62180. });
  62181. }
  62182. // Streaming sound using HTML5 Audio tag
  62183. else {
  62184. this._htmlAudioElement = new Audio(url);
  62185. this._htmlAudioElement.controls = false;
  62186. this._htmlAudioElement.loop = this.loop;
  62187. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62188. this._htmlAudioElement.preload = "auto";
  62189. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62190. _this._isReadyToPlay = true;
  62191. if (_this.autoplay) {
  62192. _this.play();
  62193. }
  62194. if (_this._readyToPlayCallback) {
  62195. _this._readyToPlayCallback();
  62196. }
  62197. });
  62198. document.body.appendChild(this._htmlAudioElement);
  62199. }
  62200. break;
  62201. }
  62202. }
  62203. break;
  62204. default:
  62205. validParameter = false;
  62206. break;
  62207. }
  62208. if (!validParameter) {
  62209. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62210. }
  62211. else {
  62212. if (!codecSupportedFound) {
  62213. this._isReadyToPlay = true;
  62214. // Simulating a ready to play event to avoid breaking code path
  62215. if (this._readyToPlayCallback) {
  62216. window.setTimeout(function () {
  62217. if (_this._readyToPlayCallback) {
  62218. _this._readyToPlayCallback();
  62219. }
  62220. }, 1000);
  62221. }
  62222. }
  62223. }
  62224. }
  62225. catch (ex) {
  62226. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62227. this._scene.mainSoundTrack.RemoveSound(this);
  62228. }
  62229. }
  62230. }
  62231. else {
  62232. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62233. this._scene.mainSoundTrack.AddSound(this);
  62234. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62235. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62236. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62237. }
  62238. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62239. if (this._readyToPlayCallback) {
  62240. window.setTimeout(function () {
  62241. if (_this._readyToPlayCallback) {
  62242. _this._readyToPlayCallback();
  62243. }
  62244. }, 1000);
  62245. }
  62246. }
  62247. }
  62248. Sound.prototype.dispose = function () {
  62249. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62250. if (this.isPlaying) {
  62251. this.stop();
  62252. }
  62253. this._isReadyToPlay = false;
  62254. if (this.soundTrackId === -1) {
  62255. this._scene.mainSoundTrack.RemoveSound(this);
  62256. }
  62257. else {
  62258. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62259. }
  62260. if (this._soundGain) {
  62261. this._soundGain.disconnect();
  62262. this._soundGain = null;
  62263. }
  62264. if (this._soundPanner) {
  62265. this._soundPanner.disconnect();
  62266. this._soundPanner = null;
  62267. }
  62268. if (this._soundSource) {
  62269. this._soundSource.disconnect();
  62270. this._soundSource = null;
  62271. }
  62272. this._audioBuffer = null;
  62273. if (this._htmlAudioElement) {
  62274. this._htmlAudioElement.pause();
  62275. this._htmlAudioElement.src = "";
  62276. document.body.removeChild(this._htmlAudioElement);
  62277. }
  62278. if (this._streamingSource) {
  62279. this._streamingSource.disconnect();
  62280. }
  62281. if (this._connectedMesh && this._registerFunc) {
  62282. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62283. this._connectedMesh = null;
  62284. }
  62285. }
  62286. };
  62287. Sound.prototype.isReady = function () {
  62288. return this._isReadyToPlay;
  62289. };
  62290. Sound.prototype._soundLoaded = function (audioData) {
  62291. var _this = this;
  62292. if (!BABYLON.Engine.audioEngine.audioContext) {
  62293. return;
  62294. }
  62295. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62296. _this._audioBuffer = buffer;
  62297. _this._isReadyToPlay = true;
  62298. if (_this.autoplay) {
  62299. _this.play();
  62300. }
  62301. if (_this._readyToPlayCallback) {
  62302. _this._readyToPlayCallback();
  62303. }
  62304. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62305. };
  62306. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62307. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62308. this._audioBuffer = audioBuffer;
  62309. this._isReadyToPlay = true;
  62310. }
  62311. };
  62312. Sound.prototype.updateOptions = function (options) {
  62313. if (options) {
  62314. this.loop = options.loop || this.loop;
  62315. this.maxDistance = options.maxDistance || this.maxDistance;
  62316. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62317. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62318. this.refDistance = options.refDistance || this.refDistance;
  62319. this.distanceModel = options.distanceModel || this.distanceModel;
  62320. this._playbackRate = options.playbackRate || this._playbackRate;
  62321. this._updateSpatialParameters();
  62322. if (this.isPlaying) {
  62323. if (this._streaming && this._htmlAudioElement) {
  62324. this._htmlAudioElement.playbackRate = this._playbackRate;
  62325. }
  62326. else {
  62327. if (this._soundSource) {
  62328. this._soundSource.playbackRate.value = this._playbackRate;
  62329. }
  62330. }
  62331. }
  62332. }
  62333. };
  62334. Sound.prototype._createSpatialParameters = function () {
  62335. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62336. if (this._scene.headphone) {
  62337. this._panningModel = "HRTF";
  62338. }
  62339. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62340. this._updateSpatialParameters();
  62341. this._soundPanner.connect(this._ouputAudioNode);
  62342. this._inputAudioNode = this._soundPanner;
  62343. }
  62344. };
  62345. Sound.prototype._updateSpatialParameters = function () {
  62346. if (this.spatialSound && this._soundPanner) {
  62347. if (this.useCustomAttenuation) {
  62348. // Tricks to disable in a way embedded Web Audio attenuation
  62349. this._soundPanner.distanceModel = "linear";
  62350. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62351. this._soundPanner.refDistance = 1;
  62352. this._soundPanner.rolloffFactor = 1;
  62353. this._soundPanner.panningModel = this._panningModel;
  62354. }
  62355. else {
  62356. this._soundPanner.distanceModel = this.distanceModel;
  62357. this._soundPanner.maxDistance = this.maxDistance;
  62358. this._soundPanner.refDistance = this.refDistance;
  62359. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62360. this._soundPanner.panningModel = this._panningModel;
  62361. }
  62362. }
  62363. };
  62364. Sound.prototype.switchPanningModelToHRTF = function () {
  62365. this._panningModel = "HRTF";
  62366. this._switchPanningModel();
  62367. };
  62368. Sound.prototype.switchPanningModelToEqualPower = function () {
  62369. this._panningModel = "equalpower";
  62370. this._switchPanningModel();
  62371. };
  62372. Sound.prototype._switchPanningModel = function () {
  62373. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62374. this._soundPanner.panningModel = this._panningModel;
  62375. }
  62376. };
  62377. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62378. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62379. if (this._isOutputConnected) {
  62380. this._ouputAudioNode.disconnect();
  62381. }
  62382. this._ouputAudioNode.connect(soundTrackAudioNode);
  62383. this._isOutputConnected = true;
  62384. }
  62385. };
  62386. /**
  62387. * Transform this sound into a directional source
  62388. * @param coneInnerAngle Size of the inner cone in degree
  62389. * @param coneOuterAngle Size of the outer cone in degree
  62390. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62391. */
  62392. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62393. if (coneOuterAngle < coneInnerAngle) {
  62394. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62395. return;
  62396. }
  62397. this._coneInnerAngle = coneInnerAngle;
  62398. this._coneOuterAngle = coneOuterAngle;
  62399. this._coneOuterGain = coneOuterGain;
  62400. this._isDirectional = true;
  62401. if (this.isPlaying && this.loop) {
  62402. this.stop();
  62403. this.play();
  62404. }
  62405. };
  62406. Sound.prototype.setPosition = function (newPosition) {
  62407. this._position = newPosition;
  62408. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62409. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62410. }
  62411. };
  62412. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62413. this._localDirection = newLocalDirection;
  62414. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62415. this._updateDirection();
  62416. }
  62417. };
  62418. Sound.prototype._updateDirection = function () {
  62419. if (!this._connectedMesh || !this._soundPanner) {
  62420. return;
  62421. }
  62422. var mat = this._connectedMesh.getWorldMatrix();
  62423. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62424. direction.normalize();
  62425. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62426. };
  62427. Sound.prototype.updateDistanceFromListener = function () {
  62428. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62429. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62430. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62431. }
  62432. };
  62433. Sound.prototype.setAttenuationFunction = function (callback) {
  62434. this._customAttenuationFunction = callback;
  62435. };
  62436. /**
  62437. * Play the sound
  62438. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62439. * @param offset (optional) Start the sound setting it at a specific time
  62440. */
  62441. Sound.prototype.play = function (time, offset) {
  62442. var _this = this;
  62443. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62444. try {
  62445. if (this._startOffset < 0) {
  62446. time = -this._startOffset;
  62447. this._startOffset = 0;
  62448. }
  62449. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62450. if (!this._soundSource || !this._streamingSource) {
  62451. if (this.spatialSound && this._soundPanner) {
  62452. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62453. if (this._isDirectional) {
  62454. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62455. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62456. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62457. if (this._connectedMesh) {
  62458. this._updateDirection();
  62459. }
  62460. else {
  62461. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62462. }
  62463. }
  62464. }
  62465. }
  62466. if (this._streaming) {
  62467. if (!this._streamingSource) {
  62468. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62469. this._htmlAudioElement.onended = function () { _this._onended(); };
  62470. this._htmlAudioElement.playbackRate = this._playbackRate;
  62471. }
  62472. this._streamingSource.disconnect();
  62473. this._streamingSource.connect(this._inputAudioNode);
  62474. if (this._htmlAudioElement) {
  62475. this._htmlAudioElement.play();
  62476. }
  62477. }
  62478. else {
  62479. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62480. this._soundSource.buffer = this._audioBuffer;
  62481. this._soundSource.connect(this._inputAudioNode);
  62482. this._soundSource.loop = this.loop;
  62483. this._soundSource.playbackRate.value = this._playbackRate;
  62484. this._soundSource.onended = function () { _this._onended(); };
  62485. if (this._soundSource.buffer) {
  62486. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62487. }
  62488. }
  62489. this._startTime = startTime;
  62490. this.isPlaying = true;
  62491. this.isPaused = false;
  62492. }
  62493. catch (ex) {
  62494. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62495. }
  62496. }
  62497. };
  62498. Sound.prototype._onended = function () {
  62499. this.isPlaying = false;
  62500. if (this.onended) {
  62501. this.onended();
  62502. }
  62503. };
  62504. /**
  62505. * Stop the sound
  62506. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62507. */
  62508. Sound.prototype.stop = function (time) {
  62509. if (this.isPlaying) {
  62510. if (this._streaming) {
  62511. if (this._htmlAudioElement) {
  62512. this._htmlAudioElement.pause();
  62513. // Test needed for Firefox or it will generate an Invalid State Error
  62514. if (this._htmlAudioElement.currentTime > 0) {
  62515. this._htmlAudioElement.currentTime = 0;
  62516. }
  62517. }
  62518. else {
  62519. this._streamingSource.disconnect();
  62520. }
  62521. }
  62522. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62523. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62524. this._soundSource.stop(stopTime);
  62525. this._soundSource.onended = function () { };
  62526. if (!this.isPaused) {
  62527. this._startOffset = 0;
  62528. }
  62529. }
  62530. this.isPlaying = false;
  62531. }
  62532. };
  62533. Sound.prototype.pause = function () {
  62534. if (this.isPlaying) {
  62535. this.isPaused = true;
  62536. if (this._streaming) {
  62537. if (this._htmlAudioElement) {
  62538. this._htmlAudioElement.pause();
  62539. }
  62540. else {
  62541. this._streamingSource.disconnect();
  62542. }
  62543. }
  62544. else if (BABYLON.Engine.audioEngine.audioContext) {
  62545. this.stop(0);
  62546. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62547. }
  62548. }
  62549. };
  62550. Sound.prototype.setVolume = function (newVolume, time) {
  62551. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62552. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62553. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62554. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62555. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62556. }
  62557. else {
  62558. this._soundGain.gain.value = newVolume;
  62559. }
  62560. }
  62561. this._volume = newVolume;
  62562. };
  62563. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62564. this._playbackRate = newPlaybackRate;
  62565. if (this.isPlaying) {
  62566. if (this._streaming && this._htmlAudioElement) {
  62567. this._htmlAudioElement.playbackRate = this._playbackRate;
  62568. }
  62569. else if (this._soundSource) {
  62570. this._soundSource.playbackRate.value = this._playbackRate;
  62571. }
  62572. }
  62573. };
  62574. Sound.prototype.getVolume = function () {
  62575. return this._volume;
  62576. };
  62577. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62578. var _this = this;
  62579. if (this._connectedMesh && this._registerFunc) {
  62580. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62581. this._registerFunc = null;
  62582. }
  62583. this._connectedMesh = meshToConnectTo;
  62584. if (!this.spatialSound) {
  62585. this.spatialSound = true;
  62586. this._createSpatialParameters();
  62587. if (this.isPlaying && this.loop) {
  62588. this.stop();
  62589. this.play();
  62590. }
  62591. }
  62592. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62593. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62594. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62595. };
  62596. Sound.prototype.detachFromMesh = function () {
  62597. if (this._connectedMesh && this._registerFunc) {
  62598. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62599. this._registerFunc = null;
  62600. this._connectedMesh = null;
  62601. }
  62602. };
  62603. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62604. if (!node.getBoundingInfo) {
  62605. return;
  62606. }
  62607. var mesh = node;
  62608. var boundingInfo = mesh.getBoundingInfo();
  62609. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62610. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62611. this._updateDirection();
  62612. }
  62613. };
  62614. Sound.prototype.clone = function () {
  62615. var _this = this;
  62616. if (!this._streaming) {
  62617. var setBufferAndRun = function () {
  62618. if (_this._isReadyToPlay) {
  62619. clonedSound._audioBuffer = _this.getAudioBuffer();
  62620. clonedSound._isReadyToPlay = true;
  62621. if (clonedSound.autoplay) {
  62622. clonedSound.play();
  62623. }
  62624. }
  62625. else {
  62626. window.setTimeout(setBufferAndRun, 300);
  62627. }
  62628. };
  62629. var currentOptions = {
  62630. autoplay: this.autoplay, loop: this.loop,
  62631. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62632. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62633. refDistance: this.refDistance, distanceModel: this.distanceModel
  62634. };
  62635. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62636. if (this.useCustomAttenuation) {
  62637. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62638. }
  62639. clonedSound.setPosition(this._position);
  62640. clonedSound.setPlaybackRate(this._playbackRate);
  62641. setBufferAndRun();
  62642. return clonedSound;
  62643. }
  62644. // Can't clone a streaming sound
  62645. else {
  62646. return null;
  62647. }
  62648. };
  62649. Sound.prototype.getAudioBuffer = function () {
  62650. return this._audioBuffer;
  62651. };
  62652. Sound.prototype.serialize = function () {
  62653. var serializationObject = {
  62654. name: this.name,
  62655. url: this.name,
  62656. autoplay: this.autoplay,
  62657. loop: this.loop,
  62658. volume: this._volume,
  62659. spatialSound: this.spatialSound,
  62660. maxDistance: this.maxDistance,
  62661. rolloffFactor: this.rolloffFactor,
  62662. refDistance: this.refDistance,
  62663. distanceModel: this.distanceModel,
  62664. playbackRate: this._playbackRate,
  62665. panningModel: this._panningModel,
  62666. soundTrackId: this.soundTrackId
  62667. };
  62668. if (this.spatialSound) {
  62669. if (this._connectedMesh)
  62670. serializationObject.connectedMeshId = this._connectedMesh.id;
  62671. serializationObject.position = this._position.asArray();
  62672. serializationObject.refDistance = this.refDistance;
  62673. serializationObject.distanceModel = this.distanceModel;
  62674. serializationObject.isDirectional = this._isDirectional;
  62675. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62676. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62677. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62678. serializationObject.coneOuterGain = this._coneOuterGain;
  62679. }
  62680. return serializationObject;
  62681. };
  62682. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62683. var soundName = parsedSound.name;
  62684. var soundUrl;
  62685. if (parsedSound.url) {
  62686. soundUrl = rootUrl + parsedSound.url;
  62687. }
  62688. else {
  62689. soundUrl = rootUrl + soundName;
  62690. }
  62691. var options = {
  62692. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62693. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62694. rolloffFactor: parsedSound.rolloffFactor,
  62695. refDistance: parsedSound.refDistance,
  62696. distanceModel: parsedSound.distanceModel,
  62697. playbackRate: parsedSound.playbackRate
  62698. };
  62699. var newSound;
  62700. if (!sourceSound) {
  62701. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62702. scene._addPendingData(newSound);
  62703. }
  62704. else {
  62705. var setBufferAndRun = function () {
  62706. if (sourceSound._isReadyToPlay) {
  62707. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62708. newSound._isReadyToPlay = true;
  62709. if (newSound.autoplay) {
  62710. newSound.play();
  62711. }
  62712. }
  62713. else {
  62714. window.setTimeout(setBufferAndRun, 300);
  62715. }
  62716. };
  62717. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62718. setBufferAndRun();
  62719. }
  62720. if (parsedSound.position) {
  62721. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62722. newSound.setPosition(soundPosition);
  62723. }
  62724. if (parsedSound.isDirectional) {
  62725. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62726. if (parsedSound.localDirectionToMesh) {
  62727. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62728. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62729. }
  62730. }
  62731. if (parsedSound.connectedMeshId) {
  62732. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62733. if (connectedMesh) {
  62734. newSound.attachToMesh(connectedMesh);
  62735. }
  62736. }
  62737. return newSound;
  62738. };
  62739. return Sound;
  62740. }());
  62741. BABYLON.Sound = Sound;
  62742. })(BABYLON || (BABYLON = {}));
  62743. //# sourceMappingURL=babylon.sound.js.map
  62744. var BABYLON;
  62745. (function (BABYLON) {
  62746. var SoundTrack = /** @class */ (function () {
  62747. function SoundTrack(scene, options) {
  62748. this.id = -1;
  62749. this._isMainTrack = false;
  62750. this._isInitialized = false;
  62751. this._scene = scene;
  62752. this.soundCollection = new Array();
  62753. this._options = options;
  62754. if (!this._isMainTrack) {
  62755. this._scene.soundTracks.push(this);
  62756. this.id = this._scene.soundTracks.length - 1;
  62757. }
  62758. }
  62759. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62760. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62761. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62762. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62763. if (this._options) {
  62764. if (this._options.volume) {
  62765. this._outputAudioNode.gain.value = this._options.volume;
  62766. }
  62767. if (this._options.mainTrack) {
  62768. this._isMainTrack = this._options.mainTrack;
  62769. }
  62770. }
  62771. this._isInitialized = true;
  62772. }
  62773. };
  62774. SoundTrack.prototype.dispose = function () {
  62775. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62776. if (this._connectedAnalyser) {
  62777. this._connectedAnalyser.stopDebugCanvas();
  62778. }
  62779. while (this.soundCollection.length) {
  62780. this.soundCollection[0].dispose();
  62781. }
  62782. if (this._outputAudioNode) {
  62783. this._outputAudioNode.disconnect();
  62784. }
  62785. this._outputAudioNode = null;
  62786. }
  62787. };
  62788. SoundTrack.prototype.AddSound = function (sound) {
  62789. if (!this._isInitialized) {
  62790. this._initializeSoundTrackAudioGraph();
  62791. }
  62792. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62793. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62794. }
  62795. if (sound.soundTrackId) {
  62796. if (sound.soundTrackId === -1) {
  62797. this._scene.mainSoundTrack.RemoveSound(sound);
  62798. }
  62799. else {
  62800. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62801. }
  62802. }
  62803. this.soundCollection.push(sound);
  62804. sound.soundTrackId = this.id;
  62805. };
  62806. SoundTrack.prototype.RemoveSound = function (sound) {
  62807. var index = this.soundCollection.indexOf(sound);
  62808. if (index !== -1) {
  62809. this.soundCollection.splice(index, 1);
  62810. }
  62811. };
  62812. SoundTrack.prototype.setVolume = function (newVolume) {
  62813. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62814. this._outputAudioNode.gain.value = newVolume;
  62815. }
  62816. };
  62817. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62818. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62819. for (var i = 0; i < this.soundCollection.length; i++) {
  62820. this.soundCollection[i].switchPanningModelToHRTF();
  62821. }
  62822. }
  62823. };
  62824. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62825. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62826. for (var i = 0; i < this.soundCollection.length; i++) {
  62827. this.soundCollection[i].switchPanningModelToEqualPower();
  62828. }
  62829. }
  62830. };
  62831. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62832. if (this._connectedAnalyser) {
  62833. this._connectedAnalyser.stopDebugCanvas();
  62834. }
  62835. this._connectedAnalyser = analyser;
  62836. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62837. this._outputAudioNode.disconnect();
  62838. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62839. }
  62840. };
  62841. return SoundTrack;
  62842. }());
  62843. BABYLON.SoundTrack = SoundTrack;
  62844. })(BABYLON || (BABYLON = {}));
  62845. //# sourceMappingURL=babylon.soundtrack.js.map
  62846. var BABYLON;
  62847. (function (BABYLON) {
  62848. /**
  62849. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62850. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62851. */
  62852. var Analyser = /** @class */ (function () {
  62853. /**
  62854. * Creates a new analyser
  62855. * @param scene defines hosting scene
  62856. */
  62857. function Analyser(scene) {
  62858. /**
  62859. * Gets or sets the smoothing
  62860. * @ignorenaming
  62861. */
  62862. this.SMOOTHING = 0.75;
  62863. /**
  62864. * Gets or sets the FFT table size
  62865. * @ignorenaming
  62866. */
  62867. this.FFT_SIZE = 512;
  62868. /**
  62869. * Gets or sets the bar graph amplitude
  62870. * @ignorenaming
  62871. */
  62872. this.BARGRAPHAMPLITUDE = 256;
  62873. /**
  62874. * Gets or sets the position of the debug canvas
  62875. * @ignorenaming
  62876. */
  62877. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62878. /**
  62879. * Gets or sets the debug canvas size
  62880. * @ignorenaming
  62881. */
  62882. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62883. this._scene = scene;
  62884. this._audioEngine = BABYLON.Engine.audioEngine;
  62885. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62886. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62887. this._webAudioAnalyser.minDecibels = -140;
  62888. this._webAudioAnalyser.maxDecibels = 0;
  62889. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62890. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62891. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62892. }
  62893. }
  62894. /**
  62895. * Get the number of data values you will have to play with for the visualization
  62896. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62897. * @returns a number
  62898. */
  62899. Analyser.prototype.getFrequencyBinCount = function () {
  62900. if (this._audioEngine.canUseWebAudio) {
  62901. return this._webAudioAnalyser.frequencyBinCount;
  62902. }
  62903. else {
  62904. return 0;
  62905. }
  62906. };
  62907. /**
  62908. * Gets the current frequency data as a byte array
  62909. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62910. * @returns a Uint8Array
  62911. */
  62912. Analyser.prototype.getByteFrequencyData = function () {
  62913. if (this._audioEngine.canUseWebAudio) {
  62914. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62915. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62916. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62917. }
  62918. return this._byteFreqs;
  62919. };
  62920. /**
  62921. * Gets the current waveform as a byte array
  62922. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62923. * @returns a Uint8Array
  62924. */
  62925. Analyser.prototype.getByteTimeDomainData = function () {
  62926. if (this._audioEngine.canUseWebAudio) {
  62927. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62928. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62929. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62930. }
  62931. return this._byteTime;
  62932. };
  62933. /**
  62934. * Gets the current frequency data as a float array
  62935. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62936. * @returns a Float32Array
  62937. */
  62938. Analyser.prototype.getFloatFrequencyData = function () {
  62939. if (this._audioEngine.canUseWebAudio) {
  62940. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62941. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62942. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62943. }
  62944. return this._floatFreqs;
  62945. };
  62946. /**
  62947. * Renders the debug canvas
  62948. */
  62949. Analyser.prototype.drawDebugCanvas = function () {
  62950. var _this = this;
  62951. if (this._audioEngine.canUseWebAudio) {
  62952. if (!this._debugCanvas) {
  62953. this._debugCanvas = document.createElement("canvas");
  62954. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62955. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62956. this._debugCanvas.style.position = "absolute";
  62957. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62958. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62959. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62960. document.body.appendChild(this._debugCanvas);
  62961. this._registerFunc = function () {
  62962. _this.drawDebugCanvas();
  62963. };
  62964. this._scene.registerBeforeRender(this._registerFunc);
  62965. }
  62966. if (this._registerFunc && this._debugCanvasContext) {
  62967. var workingArray = this.getByteFrequencyData();
  62968. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62969. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62970. // Draw the frequency domain chart.
  62971. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62972. var value = workingArray[i];
  62973. var percent = value / this.BARGRAPHAMPLITUDE;
  62974. var height = this.DEBUGCANVASSIZE.height * percent;
  62975. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62976. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62977. var hue = i / this.getFrequencyBinCount() * 360;
  62978. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62979. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62980. }
  62981. }
  62982. }
  62983. };
  62984. /**
  62985. * Stops rendering the debug canvas and removes it
  62986. */
  62987. Analyser.prototype.stopDebugCanvas = function () {
  62988. if (this._debugCanvas) {
  62989. if (this._registerFunc) {
  62990. this._scene.unregisterBeforeRender(this._registerFunc);
  62991. this._registerFunc = null;
  62992. }
  62993. document.body.removeChild(this._debugCanvas);
  62994. this._debugCanvas = null;
  62995. this._debugCanvasContext = null;
  62996. }
  62997. };
  62998. /**
  62999. * Connects two audio nodes
  63000. * @param inputAudioNode defines first node to connect
  63001. * @param outputAudioNode defines second node to connect
  63002. */
  63003. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63004. if (this._audioEngine.canUseWebAudio) {
  63005. inputAudioNode.connect(this._webAudioAnalyser);
  63006. this._webAudioAnalyser.connect(outputAudioNode);
  63007. }
  63008. };
  63009. /**
  63010. * Releases all associated resources
  63011. */
  63012. Analyser.prototype.dispose = function () {
  63013. if (this._audioEngine.canUseWebAudio) {
  63014. this._webAudioAnalyser.disconnect();
  63015. }
  63016. };
  63017. return Analyser;
  63018. }());
  63019. BABYLON.Analyser = Analyser;
  63020. })(BABYLON || (BABYLON = {}));
  63021. //# sourceMappingURL=babylon.analyser.js.map
  63022. var BABYLON;
  63023. (function (BABYLON) {
  63024. var CubeTexture = /** @class */ (function (_super) {
  63025. __extends(CubeTexture, _super);
  63026. /**
  63027. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63028. * as prefiltered data.
  63029. * @param rootUrl defines the url of the texture or the root name of the six images
  63030. * @param scene defines the scene the texture is attached to
  63031. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63032. * @param noMipmap defines if mipmaps should be created or not
  63033. * @param files defines the six files to load for the different faces
  63034. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63035. * @param onError defines a callback triggered in case of error during load
  63036. * @param format defines the internal format to use for the texture once loaded
  63037. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63038. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63039. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63040. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63041. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63042. * @return the cube texture
  63043. */
  63044. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63045. if (extensions === void 0) { extensions = null; }
  63046. if (noMipmap === void 0) { noMipmap = false; }
  63047. if (files === void 0) { files = null; }
  63048. if (onLoad === void 0) { onLoad = null; }
  63049. if (onError === void 0) { onError = null; }
  63050. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63051. if (prefiltered === void 0) { prefiltered = false; }
  63052. if (forcedExtension === void 0) { forcedExtension = null; }
  63053. if (createPolynomials === void 0) { createPolynomials = false; }
  63054. if (lodScale === void 0) { lodScale = 0.8; }
  63055. if (lodOffset === void 0) { lodOffset = 0; }
  63056. var _this = _super.call(this, scene) || this;
  63057. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63058. /**
  63059. * Gets or sets the center of the bounding box associated with the cube texture
  63060. * It must define where the camera used to render the texture was set
  63061. */
  63062. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63063. _this._rotationY = 0;
  63064. /** @hidden */
  63065. _this._prefiltered = false;
  63066. _this.name = rootUrl;
  63067. _this.url = rootUrl;
  63068. _this._noMipmap = noMipmap;
  63069. _this.hasAlpha = false;
  63070. _this._format = format;
  63071. _this.isCube = true;
  63072. _this._textureMatrix = BABYLON.Matrix.Identity();
  63073. _this._createPolynomials = createPolynomials;
  63074. if (!rootUrl && !files) {
  63075. return _this;
  63076. }
  63077. var lastDot = rootUrl.lastIndexOf(".");
  63078. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63079. var isDDS = (extension === ".dds");
  63080. var isEnv = (extension === ".env");
  63081. if (isEnv) {
  63082. _this.gammaSpace = false;
  63083. _this._prefiltered = false;
  63084. }
  63085. else {
  63086. _this._prefiltered = prefiltered;
  63087. if (prefiltered) {
  63088. _this.gammaSpace = false;
  63089. }
  63090. }
  63091. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63092. if (!files) {
  63093. if (!isEnv && !isDDS && !extensions) {
  63094. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63095. }
  63096. files = [];
  63097. if (extensions) {
  63098. for (var index = 0; index < extensions.length; index++) {
  63099. files.push(rootUrl + extensions[index]);
  63100. }
  63101. }
  63102. }
  63103. _this._files = files;
  63104. if (!_this._texture) {
  63105. if (!scene.useDelayedTextureLoading) {
  63106. if (prefiltered) {
  63107. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63108. }
  63109. else {
  63110. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63111. }
  63112. }
  63113. else {
  63114. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63115. }
  63116. }
  63117. else if (onLoad) {
  63118. if (_this._texture.isReady) {
  63119. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63120. }
  63121. else {
  63122. _this._texture.onLoadedObservable.add(onLoad);
  63123. }
  63124. }
  63125. return _this;
  63126. }
  63127. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63128. get: function () {
  63129. return this._boundingBoxSize;
  63130. },
  63131. /**
  63132. * Gets or sets the size of the bounding box associated with the cube texture
  63133. * When defined, the cubemap will switch to local mode
  63134. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63135. * @example https://www.babylonjs-playground.com/#RNASML
  63136. */
  63137. set: function (value) {
  63138. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63139. return;
  63140. }
  63141. this._boundingBoxSize = value;
  63142. var scene = this.getScene();
  63143. if (scene) {
  63144. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63145. }
  63146. },
  63147. enumerable: true,
  63148. configurable: true
  63149. });
  63150. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63151. /**
  63152. * Gets texture matrix rotation angle around Y axis radians.
  63153. */
  63154. get: function () {
  63155. return this._rotationY;
  63156. },
  63157. /**
  63158. * Sets texture matrix rotation angle around Y axis in radians.
  63159. */
  63160. set: function (value) {
  63161. this._rotationY = value;
  63162. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63163. },
  63164. enumerable: true,
  63165. configurable: true
  63166. });
  63167. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63168. var rootUrlKey = "";
  63169. files.forEach(function (url) { return rootUrlKey += url; });
  63170. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63171. };
  63172. /**
  63173. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63174. * @param url defines the url of the prefiltered texture
  63175. * @param scene defines the scene the texture is attached to
  63176. * @param forcedExtension defines the extension of the file if different from the url
  63177. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63178. * @return the prefiltered texture
  63179. */
  63180. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63181. if (forcedExtension === void 0) { forcedExtension = null; }
  63182. if (createPolynomials === void 0) { createPolynomials = true; }
  63183. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63184. };
  63185. // Methods
  63186. CubeTexture.prototype.delayLoad = function () {
  63187. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63188. return;
  63189. }
  63190. var scene = this.getScene();
  63191. if (!scene) {
  63192. return;
  63193. }
  63194. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63195. this._texture = this._getFromCache(this.url, this._noMipmap);
  63196. if (!this._texture) {
  63197. if (this._prefiltered) {
  63198. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63199. }
  63200. else {
  63201. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63202. }
  63203. }
  63204. };
  63205. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63206. return this._textureMatrix;
  63207. };
  63208. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63209. this._textureMatrix = value;
  63210. };
  63211. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63212. var texture = BABYLON.SerializationHelper.Parse(function () {
  63213. var prefiltered = false;
  63214. if (parsedTexture.prefiltered) {
  63215. prefiltered = parsedTexture.prefiltered;
  63216. }
  63217. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63218. }, parsedTexture, scene);
  63219. // Local Cubemaps
  63220. if (parsedTexture.boundingBoxPosition) {
  63221. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63222. }
  63223. if (parsedTexture.boundingBoxSize) {
  63224. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63225. }
  63226. // Animations
  63227. if (parsedTexture.animations) {
  63228. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63229. var parsedAnimation = parsedTexture.animations[animationIndex];
  63230. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63231. }
  63232. }
  63233. return texture;
  63234. };
  63235. CubeTexture.prototype.clone = function () {
  63236. var _this = this;
  63237. return BABYLON.SerializationHelper.Clone(function () {
  63238. var scene = _this.getScene();
  63239. if (!scene) {
  63240. return _this;
  63241. }
  63242. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63243. }, this);
  63244. };
  63245. __decorate([
  63246. BABYLON.serialize("rotationY")
  63247. ], CubeTexture.prototype, "_rotationY", void 0);
  63248. return CubeTexture;
  63249. }(BABYLON.BaseTexture));
  63250. BABYLON.CubeTexture = CubeTexture;
  63251. })(BABYLON || (BABYLON = {}));
  63252. //# sourceMappingURL=babylon.cubeTexture.js.map
  63253. var BABYLON;
  63254. (function (BABYLON) {
  63255. var RenderTargetTexture = /** @class */ (function (_super) {
  63256. __extends(RenderTargetTexture, _super);
  63257. /**
  63258. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63259. * or used a shadow, depth texture...
  63260. * @param name The friendly name of the texture
  63261. * @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)
  63262. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63263. * @param generateMipMaps True if mip maps need to be generated after render.
  63264. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63265. * @param type The type of the buffer in the RTT (int, half float, float...)
  63266. * @param isCube True if a cube texture needs to be created
  63267. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63268. * @param generateDepthBuffer True to generate a depth buffer
  63269. * @param generateStencilBuffer True to generate a stencil buffer
  63270. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63271. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63272. */
  63273. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63274. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63275. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63276. if (isCube === void 0) { isCube = false; }
  63277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63278. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63279. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63280. if (isMulti === void 0) { isMulti = false; }
  63281. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63282. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63283. _this.isCube = isCube;
  63284. /**
  63285. * Use this list to define the list of mesh you want to render.
  63286. */
  63287. _this.renderList = new Array();
  63288. _this.renderParticles = true;
  63289. _this.renderSprites = false;
  63290. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63291. _this.ignoreCameraViewport = false;
  63292. // Events
  63293. /**
  63294. * An event triggered when the texture is unbind.
  63295. */
  63296. _this.onBeforeBindObservable = new BABYLON.Observable();
  63297. /**
  63298. * An event triggered when the texture is unbind.
  63299. */
  63300. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63301. /**
  63302. * An event triggered before rendering the texture
  63303. */
  63304. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63305. /**
  63306. * An event triggered after rendering the texture
  63307. */
  63308. _this.onAfterRenderObservable = new BABYLON.Observable();
  63309. /**
  63310. * An event triggered after the texture clear
  63311. */
  63312. _this.onClearObservable = new BABYLON.Observable();
  63313. _this._currentRefreshId = -1;
  63314. _this._refreshRate = 1;
  63315. _this._samples = 1;
  63316. /**
  63317. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63318. * It must define where the camera used to render the texture is set
  63319. */
  63320. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63321. scene = _this.getScene();
  63322. if (!scene) {
  63323. return _this;
  63324. }
  63325. _this._engine = scene.getEngine();
  63326. _this.name = name;
  63327. _this.isRenderTarget = true;
  63328. _this._initialSizeParameter = size;
  63329. _this._processSizeParameter(size);
  63330. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63331. });
  63332. _this._generateMipMaps = generateMipMaps ? true : false;
  63333. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63334. // Rendering groups
  63335. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63336. if (isMulti) {
  63337. return _this;
  63338. }
  63339. _this._renderTargetOptions = {
  63340. generateMipMaps: generateMipMaps,
  63341. type: type,
  63342. format: format,
  63343. samplingMode: samplingMode,
  63344. generateDepthBuffer: generateDepthBuffer,
  63345. generateStencilBuffer: generateStencilBuffer
  63346. };
  63347. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63348. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63349. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63350. }
  63351. if (isCube) {
  63352. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63353. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63354. _this._textureMatrix = BABYLON.Matrix.Identity();
  63355. }
  63356. else {
  63357. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63358. }
  63359. return _this;
  63360. }
  63361. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63362. get: function () {
  63363. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63364. },
  63365. enumerable: true,
  63366. configurable: true
  63367. });
  63368. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63369. get: function () {
  63370. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63371. },
  63372. enumerable: true,
  63373. configurable: true
  63374. });
  63375. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63376. get: function () {
  63377. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63378. },
  63379. enumerable: true,
  63380. configurable: true
  63381. });
  63382. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63383. set: function (callback) {
  63384. if (this._onAfterUnbindObserver) {
  63385. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63386. }
  63387. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63388. },
  63389. enumerable: true,
  63390. configurable: true
  63391. });
  63392. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63393. set: function (callback) {
  63394. if (this._onBeforeRenderObserver) {
  63395. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63396. }
  63397. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63398. },
  63399. enumerable: true,
  63400. configurable: true
  63401. });
  63402. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63403. set: function (callback) {
  63404. if (this._onAfterRenderObserver) {
  63405. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63406. }
  63407. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63408. },
  63409. enumerable: true,
  63410. configurable: true
  63411. });
  63412. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63413. set: function (callback) {
  63414. if (this._onClearObserver) {
  63415. this.onClearObservable.remove(this._onClearObserver);
  63416. }
  63417. this._onClearObserver = this.onClearObservable.add(callback);
  63418. },
  63419. enumerable: true,
  63420. configurable: true
  63421. });
  63422. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63423. get: function () {
  63424. return this._renderTargetOptions;
  63425. },
  63426. enumerable: true,
  63427. configurable: true
  63428. });
  63429. RenderTargetTexture.prototype._onRatioRescale = function () {
  63430. if (this._sizeRatio) {
  63431. this.resize(this._initialSizeParameter);
  63432. }
  63433. };
  63434. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63435. get: function () {
  63436. return this._boundingBoxSize;
  63437. },
  63438. /**
  63439. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63440. * When defined, the cubemap will switch to local mode
  63441. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63442. * @example https://www.babylonjs-playground.com/#RNASML
  63443. */
  63444. set: function (value) {
  63445. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63446. return;
  63447. }
  63448. this._boundingBoxSize = value;
  63449. var scene = this.getScene();
  63450. if (scene) {
  63451. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63452. }
  63453. },
  63454. enumerable: true,
  63455. configurable: true
  63456. });
  63457. /**
  63458. * Creates a depth stencil texture.
  63459. * This is only available in WebGL 2 or with the depth texture extension available.
  63460. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63461. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63462. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63463. */
  63464. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63465. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63466. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63467. if (generateStencil === void 0) { generateStencil = false; }
  63468. if (!this.getScene()) {
  63469. return;
  63470. }
  63471. var engine = this.getScene().getEngine();
  63472. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63473. bilinearFiltering: bilinearFiltering,
  63474. comparisonFunction: comparisonFunction,
  63475. generateStencil: generateStencil,
  63476. isCube: this.isCube
  63477. });
  63478. engine.setFrameBufferDepthStencilTexture(this);
  63479. };
  63480. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63481. if (size.ratio) {
  63482. this._sizeRatio = size.ratio;
  63483. this._size = {
  63484. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63485. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63486. };
  63487. }
  63488. else {
  63489. this._size = size;
  63490. }
  63491. };
  63492. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63493. get: function () {
  63494. return this._samples;
  63495. },
  63496. set: function (value) {
  63497. if (this._samples === value) {
  63498. return;
  63499. }
  63500. var scene = this.getScene();
  63501. if (!scene) {
  63502. return;
  63503. }
  63504. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63505. },
  63506. enumerable: true,
  63507. configurable: true
  63508. });
  63509. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63510. this._currentRefreshId = -1;
  63511. };
  63512. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63513. get: function () {
  63514. return this._refreshRate;
  63515. },
  63516. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63517. set: function (value) {
  63518. this._refreshRate = value;
  63519. this.resetRefreshCounter();
  63520. },
  63521. enumerable: true,
  63522. configurable: true
  63523. });
  63524. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63525. if (!this._postProcessManager) {
  63526. var scene = this.getScene();
  63527. if (!scene) {
  63528. return;
  63529. }
  63530. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63531. this._postProcesses = new Array();
  63532. }
  63533. this._postProcesses.push(postProcess);
  63534. this._postProcesses[0].autoClear = false;
  63535. };
  63536. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63537. if (!this._postProcesses) {
  63538. return;
  63539. }
  63540. if (dispose) {
  63541. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63542. var postProcess = _a[_i];
  63543. postProcess.dispose();
  63544. }
  63545. }
  63546. this._postProcesses = [];
  63547. };
  63548. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63549. if (!this._postProcesses) {
  63550. return;
  63551. }
  63552. var index = this._postProcesses.indexOf(postProcess);
  63553. if (index === -1) {
  63554. return;
  63555. }
  63556. this._postProcesses.splice(index, 1);
  63557. if (this._postProcesses.length > 0) {
  63558. this._postProcesses[0].autoClear = false;
  63559. }
  63560. };
  63561. RenderTargetTexture.prototype._shouldRender = function () {
  63562. if (this._currentRefreshId === -1) { // At least render once
  63563. this._currentRefreshId = 1;
  63564. return true;
  63565. }
  63566. if (this.refreshRate === this._currentRefreshId) {
  63567. this._currentRefreshId = 1;
  63568. return true;
  63569. }
  63570. this._currentRefreshId++;
  63571. return false;
  63572. };
  63573. RenderTargetTexture.prototype.getRenderSize = function () {
  63574. if (this._size.width) {
  63575. return this._size.width;
  63576. }
  63577. return this._size;
  63578. };
  63579. RenderTargetTexture.prototype.getRenderWidth = function () {
  63580. if (this._size.width) {
  63581. return this._size.width;
  63582. }
  63583. return this._size;
  63584. };
  63585. RenderTargetTexture.prototype.getRenderHeight = function () {
  63586. if (this._size.width) {
  63587. return this._size.height;
  63588. }
  63589. return this._size;
  63590. };
  63591. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63592. get: function () {
  63593. return true;
  63594. },
  63595. enumerable: true,
  63596. configurable: true
  63597. });
  63598. RenderTargetTexture.prototype.scale = function (ratio) {
  63599. var newSize = this.getRenderSize() * ratio;
  63600. this.resize(newSize);
  63601. };
  63602. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63603. if (this.isCube) {
  63604. return this._textureMatrix;
  63605. }
  63606. return _super.prototype.getReflectionTextureMatrix.call(this);
  63607. };
  63608. RenderTargetTexture.prototype.resize = function (size) {
  63609. this.releaseInternalTexture();
  63610. var scene = this.getScene();
  63611. if (!scene) {
  63612. return;
  63613. }
  63614. this._processSizeParameter(size);
  63615. if (this.isCube) {
  63616. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63617. }
  63618. else {
  63619. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63620. }
  63621. };
  63622. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63623. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63624. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63625. var scene = this.getScene();
  63626. if (!scene) {
  63627. return;
  63628. }
  63629. var engine = scene.getEngine();
  63630. if (this.useCameraPostProcesses !== undefined) {
  63631. useCameraPostProcess = this.useCameraPostProcesses;
  63632. }
  63633. if (this._waitingRenderList) {
  63634. this.renderList = [];
  63635. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63636. var id = this._waitingRenderList[index];
  63637. var mesh_1 = scene.getMeshByID(id);
  63638. if (mesh_1) {
  63639. this.renderList.push(mesh_1);
  63640. }
  63641. }
  63642. delete this._waitingRenderList;
  63643. }
  63644. // Is predicate defined?
  63645. if (this.renderListPredicate) {
  63646. if (this.renderList) {
  63647. this.renderList.splice(0); // Clear previous renderList
  63648. }
  63649. else {
  63650. this.renderList = [];
  63651. }
  63652. var scene = this.getScene();
  63653. if (!scene) {
  63654. return;
  63655. }
  63656. var sceneMeshes = scene.meshes;
  63657. for (var index = 0; index < sceneMeshes.length; index++) {
  63658. var mesh = sceneMeshes[index];
  63659. if (this.renderListPredicate(mesh)) {
  63660. this.renderList.push(mesh);
  63661. }
  63662. }
  63663. }
  63664. this.onBeforeBindObservable.notifyObservers(this);
  63665. // Set custom projection.
  63666. // Needs to be before binding to prevent changing the aspect ratio.
  63667. var camera;
  63668. if (this.activeCamera) {
  63669. camera = this.activeCamera;
  63670. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63671. if (this.activeCamera !== scene.activeCamera) {
  63672. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63673. }
  63674. }
  63675. else {
  63676. camera = scene.activeCamera;
  63677. if (camera) {
  63678. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63679. }
  63680. }
  63681. // Prepare renderingManager
  63682. this._renderingManager.reset();
  63683. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63684. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63685. var sceneRenderId = scene.getRenderId();
  63686. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63687. var mesh = currentRenderList[meshIndex];
  63688. if (mesh) {
  63689. if (!mesh.isReady(this.refreshRate === 0)) {
  63690. this.resetRefreshCounter();
  63691. continue;
  63692. }
  63693. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63694. var isMasked = void 0;
  63695. if (!this.renderList && camera) {
  63696. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63697. }
  63698. else {
  63699. isMasked = false;
  63700. }
  63701. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63702. mesh._activate(sceneRenderId);
  63703. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63704. var subMesh = mesh.subMeshes[subIndex];
  63705. scene._activeIndices.addCount(subMesh.indexCount, false);
  63706. this._renderingManager.dispatch(subMesh, mesh);
  63707. }
  63708. }
  63709. }
  63710. }
  63711. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63712. var particleSystem = scene.particleSystems[particleIndex];
  63713. var emitter = particleSystem.emitter;
  63714. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63715. continue;
  63716. }
  63717. if (currentRenderList.indexOf(emitter) >= 0) {
  63718. this._renderingManager.dispatchParticles(particleSystem);
  63719. }
  63720. }
  63721. if (this.isCube) {
  63722. for (var face = 0; face < 6; face++) {
  63723. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63724. scene.incrementRenderId();
  63725. scene.resetCachedMaterial();
  63726. }
  63727. }
  63728. else {
  63729. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63730. }
  63731. this.onAfterUnbindObservable.notifyObservers(this);
  63732. if (scene.activeCamera) {
  63733. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63734. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63735. }
  63736. engine.setViewport(scene.activeCamera.viewport);
  63737. }
  63738. scene.resetCachedMaterial();
  63739. };
  63740. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63741. var minimum = 128;
  63742. var x = renderDimension * scale;
  63743. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63744. // Ensure we don't exceed the render dimension (while staying POT)
  63745. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63746. };
  63747. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63748. var _this = this;
  63749. if (!this._texture) {
  63750. return;
  63751. }
  63752. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63753. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63754. });
  63755. };
  63756. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63757. var scene = this.getScene();
  63758. if (!scene) {
  63759. return;
  63760. }
  63761. var engine = scene.getEngine();
  63762. if (!this._texture) {
  63763. return;
  63764. }
  63765. // Bind
  63766. if (this._postProcessManager) {
  63767. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63768. }
  63769. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63770. if (this._texture) {
  63771. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63772. }
  63773. }
  63774. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63775. // Clear
  63776. if (this.onClearObservable.hasObservers()) {
  63777. this.onClearObservable.notifyObservers(engine);
  63778. }
  63779. else {
  63780. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63781. }
  63782. if (!this._doNotChangeAspectRatio) {
  63783. scene.updateTransformMatrix(true);
  63784. }
  63785. // Render
  63786. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63787. if (this._postProcessManager) {
  63788. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63789. }
  63790. else if (useCameraPostProcess) {
  63791. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63792. }
  63793. if (!this._doNotChangeAspectRatio) {
  63794. scene.updateTransformMatrix(true);
  63795. }
  63796. // Dump ?
  63797. if (dumpForDebug) {
  63798. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63799. }
  63800. // Unbind
  63801. if (!this.isCube || faceIndex === 5) {
  63802. if (this.isCube) {
  63803. if (faceIndex === 5) {
  63804. engine.generateMipMapsForCubemap(this._texture);
  63805. }
  63806. }
  63807. this.unbindFrameBuffer(engine, faceIndex);
  63808. }
  63809. else {
  63810. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63811. }
  63812. };
  63813. /**
  63814. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63815. * This allowed control for front to back rendering or reversly depending of the special needs.
  63816. *
  63817. * @param renderingGroupId The rendering group id corresponding to its index
  63818. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63819. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63820. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63821. */
  63822. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63823. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63824. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63825. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63826. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63827. };
  63828. /**
  63829. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63830. *
  63831. * @param renderingGroupId The rendering group id corresponding to its index
  63832. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63833. */
  63834. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63835. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63836. };
  63837. RenderTargetTexture.prototype.clone = function () {
  63838. var textureSize = this.getSize();
  63839. 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);
  63840. // Base texture
  63841. newTexture.hasAlpha = this.hasAlpha;
  63842. newTexture.level = this.level;
  63843. // RenderTarget Texture
  63844. newTexture.coordinatesMode = this.coordinatesMode;
  63845. if (this.renderList) {
  63846. newTexture.renderList = this.renderList.slice(0);
  63847. }
  63848. return newTexture;
  63849. };
  63850. RenderTargetTexture.prototype.serialize = function () {
  63851. if (!this.name) {
  63852. return null;
  63853. }
  63854. var serializationObject = _super.prototype.serialize.call(this);
  63855. serializationObject.renderTargetSize = this.getRenderSize();
  63856. serializationObject.renderList = [];
  63857. if (this.renderList) {
  63858. for (var index = 0; index < this.renderList.length; index++) {
  63859. serializationObject.renderList.push(this.renderList[index].id);
  63860. }
  63861. }
  63862. return serializationObject;
  63863. };
  63864. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63865. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63866. var objBuffer = this.getInternalTexture();
  63867. var scene = this.getScene();
  63868. if (objBuffer && scene) {
  63869. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63870. }
  63871. };
  63872. RenderTargetTexture.prototype.dispose = function () {
  63873. if (this._postProcessManager) {
  63874. this._postProcessManager.dispose();
  63875. this._postProcessManager = null;
  63876. }
  63877. this.clearPostProcesses(true);
  63878. if (this._resizeObserver) {
  63879. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63880. this._resizeObserver = null;
  63881. }
  63882. this.renderList = null;
  63883. // Remove from custom render targets
  63884. var scene = this.getScene();
  63885. if (!scene) {
  63886. return;
  63887. }
  63888. var index = scene.customRenderTargets.indexOf(this);
  63889. if (index >= 0) {
  63890. scene.customRenderTargets.splice(index, 1);
  63891. }
  63892. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63893. var camera = _a[_i];
  63894. index = camera.customRenderTargets.indexOf(this);
  63895. if (index >= 0) {
  63896. camera.customRenderTargets.splice(index, 1);
  63897. }
  63898. }
  63899. _super.prototype.dispose.call(this);
  63900. };
  63901. RenderTargetTexture.prototype._rebuild = function () {
  63902. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63903. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63904. }
  63905. if (this._postProcessManager) {
  63906. this._postProcessManager._rebuild();
  63907. }
  63908. };
  63909. /**
  63910. * Clear the info related to rendering groups preventing retention point in material dispose.
  63911. */
  63912. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63913. if (this._renderingManager) {
  63914. this._renderingManager.freeRenderingGroups();
  63915. }
  63916. };
  63917. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63918. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63919. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63920. return RenderTargetTexture;
  63921. }(BABYLON.Texture));
  63922. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63923. })(BABYLON || (BABYLON = {}));
  63924. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63925. var BABYLON;
  63926. (function (BABYLON) {
  63927. ;
  63928. var MultiRenderTarget = /** @class */ (function (_super) {
  63929. __extends(MultiRenderTarget, _super);
  63930. function MultiRenderTarget(name, size, count, scene, options) {
  63931. var _this = this;
  63932. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63933. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63934. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63935. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63936. _this._engine = scene.getEngine();
  63937. if (!_this.isSupported) {
  63938. _this.dispose();
  63939. return;
  63940. }
  63941. var types = [];
  63942. var samplingModes = [];
  63943. for (var i = 0; i < count; i++) {
  63944. if (options && options.types && options.types[i] !== undefined) {
  63945. types.push(options.types[i]);
  63946. }
  63947. else {
  63948. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63949. }
  63950. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63951. samplingModes.push(options.samplingModes[i]);
  63952. }
  63953. else {
  63954. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63955. }
  63956. }
  63957. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63958. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63959. _this._size = size;
  63960. _this._multiRenderTargetOptions = {
  63961. samplingModes: samplingModes,
  63962. generateMipMaps: generateMipMaps,
  63963. generateDepthBuffer: generateDepthBuffer,
  63964. generateStencilBuffer: generateStencilBuffer,
  63965. generateDepthTexture: generateDepthTexture,
  63966. types: types,
  63967. textureCount: count
  63968. };
  63969. _this._createInternalTextures();
  63970. _this._createTextures();
  63971. return _this;
  63972. }
  63973. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63974. get: function () {
  63975. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63976. },
  63977. enumerable: true,
  63978. configurable: true
  63979. });
  63980. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63981. get: function () {
  63982. return this._textures;
  63983. },
  63984. enumerable: true,
  63985. configurable: true
  63986. });
  63987. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63988. get: function () {
  63989. return this._textures[this._textures.length - 1];
  63990. },
  63991. enumerable: true,
  63992. configurable: true
  63993. });
  63994. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63995. set: function (wrap) {
  63996. if (this._textures) {
  63997. for (var i = 0; i < this._textures.length; i++) {
  63998. this._textures[i].wrapU = wrap;
  63999. }
  64000. }
  64001. },
  64002. enumerable: true,
  64003. configurable: true
  64004. });
  64005. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64006. set: function (wrap) {
  64007. if (this._textures) {
  64008. for (var i = 0; i < this._textures.length; i++) {
  64009. this._textures[i].wrapV = wrap;
  64010. }
  64011. }
  64012. },
  64013. enumerable: true,
  64014. configurable: true
  64015. });
  64016. MultiRenderTarget.prototype._rebuild = function () {
  64017. this.releaseInternalTextures();
  64018. this._createInternalTextures();
  64019. for (var i = 0; i < this._internalTextures.length; i++) {
  64020. var texture = this._textures[i];
  64021. texture._texture = this._internalTextures[i];
  64022. }
  64023. // Keeps references to frame buffer and stencil/depth buffer
  64024. this._texture = this._internalTextures[0];
  64025. };
  64026. MultiRenderTarget.prototype._createInternalTextures = function () {
  64027. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64028. };
  64029. MultiRenderTarget.prototype._createTextures = function () {
  64030. this._textures = [];
  64031. for (var i = 0; i < this._internalTextures.length; i++) {
  64032. var texture = new BABYLON.Texture(null, this.getScene());
  64033. texture._texture = this._internalTextures[i];
  64034. this._textures.push(texture);
  64035. }
  64036. // Keeps references to frame buffer and stencil/depth buffer
  64037. this._texture = this._internalTextures[0];
  64038. };
  64039. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64040. get: function () {
  64041. return this._samples;
  64042. },
  64043. set: function (value) {
  64044. if (this._samples === value) {
  64045. return;
  64046. }
  64047. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64048. },
  64049. enumerable: true,
  64050. configurable: true
  64051. });
  64052. MultiRenderTarget.prototype.resize = function (size) {
  64053. this.releaseInternalTextures();
  64054. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64055. this._createInternalTextures();
  64056. };
  64057. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64058. var _this = this;
  64059. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64060. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64061. });
  64062. };
  64063. MultiRenderTarget.prototype.dispose = function () {
  64064. this.releaseInternalTextures();
  64065. _super.prototype.dispose.call(this);
  64066. };
  64067. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64068. if (!this._internalTextures) {
  64069. return;
  64070. }
  64071. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64072. if (this._internalTextures[i] !== undefined) {
  64073. this._internalTextures[i].dispose();
  64074. this._internalTextures.splice(i, 1);
  64075. }
  64076. }
  64077. };
  64078. return MultiRenderTarget;
  64079. }(BABYLON.RenderTargetTexture));
  64080. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64081. })(BABYLON || (BABYLON = {}));
  64082. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64083. var BABYLON;
  64084. (function (BABYLON) {
  64085. var MirrorTexture = /** @class */ (function (_super) {
  64086. __extends(MirrorTexture, _super);
  64087. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64088. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64089. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64090. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64091. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64092. _this.scene = scene;
  64093. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64094. _this._transformMatrix = BABYLON.Matrix.Zero();
  64095. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64096. _this._adaptiveBlurKernel = 0;
  64097. _this._blurKernelX = 0;
  64098. _this._blurKernelY = 0;
  64099. _this._blurRatio = 1.0;
  64100. _this.ignoreCameraViewport = true;
  64101. _this._updateGammaSpace();
  64102. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64103. _this._updateGammaSpace;
  64104. });
  64105. _this.onBeforeRenderObservable.add(function () {
  64106. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64107. _this._savedViewMatrix = scene.getViewMatrix();
  64108. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64109. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64110. scene.clipPlane = _this.mirrorPlane;
  64111. scene.getEngine().cullBackFaces = false;
  64112. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64113. });
  64114. _this.onAfterRenderObservable.add(function () {
  64115. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64116. scene.getEngine().cullBackFaces = true;
  64117. scene._mirroredCameraPosition = null;
  64118. delete scene.clipPlane;
  64119. });
  64120. return _this;
  64121. }
  64122. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64123. get: function () {
  64124. return this._blurRatio;
  64125. },
  64126. set: function (value) {
  64127. if (this._blurRatio === value) {
  64128. return;
  64129. }
  64130. this._blurRatio = value;
  64131. this._preparePostProcesses();
  64132. },
  64133. enumerable: true,
  64134. configurable: true
  64135. });
  64136. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64137. set: function (value) {
  64138. this._adaptiveBlurKernel = value;
  64139. this._autoComputeBlurKernel();
  64140. },
  64141. enumerable: true,
  64142. configurable: true
  64143. });
  64144. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64145. set: function (value) {
  64146. this.blurKernelX = value;
  64147. this.blurKernelY = value;
  64148. },
  64149. enumerable: true,
  64150. configurable: true
  64151. });
  64152. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64153. get: function () {
  64154. return this._blurKernelX;
  64155. },
  64156. set: function (value) {
  64157. if (this._blurKernelX === value) {
  64158. return;
  64159. }
  64160. this._blurKernelX = value;
  64161. this._preparePostProcesses();
  64162. },
  64163. enumerable: true,
  64164. configurable: true
  64165. });
  64166. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64167. get: function () {
  64168. return this._blurKernelY;
  64169. },
  64170. set: function (value) {
  64171. if (this._blurKernelY === value) {
  64172. return;
  64173. }
  64174. this._blurKernelY = value;
  64175. this._preparePostProcesses();
  64176. },
  64177. enumerable: true,
  64178. configurable: true
  64179. });
  64180. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64181. var engine = this.getScene().getEngine();
  64182. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64183. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64184. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64185. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64186. };
  64187. MirrorTexture.prototype._onRatioRescale = function () {
  64188. if (this._sizeRatio) {
  64189. this.resize(this._initialSizeParameter);
  64190. if (!this._adaptiveBlurKernel) {
  64191. this._preparePostProcesses();
  64192. }
  64193. }
  64194. if (this._adaptiveBlurKernel) {
  64195. this._autoComputeBlurKernel();
  64196. }
  64197. };
  64198. MirrorTexture.prototype._updateGammaSpace = function () {
  64199. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64200. };
  64201. MirrorTexture.prototype._preparePostProcesses = function () {
  64202. this.clearPostProcesses(true);
  64203. if (this._blurKernelX && this._blurKernelY) {
  64204. var engine = this.getScene().getEngine();
  64205. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64206. 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);
  64207. this._blurX.autoClear = false;
  64208. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64209. this._blurX.inputTexture = this._texture;
  64210. }
  64211. else {
  64212. this._blurX.alwaysForcePOT = true;
  64213. }
  64214. 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);
  64215. this._blurY.autoClear = false;
  64216. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64217. this.addPostProcess(this._blurX);
  64218. this.addPostProcess(this._blurY);
  64219. }
  64220. else {
  64221. if (this._blurY) {
  64222. this.removePostProcess(this._blurY);
  64223. this._blurY.dispose();
  64224. this._blurY = null;
  64225. }
  64226. if (this._blurX) {
  64227. this.removePostProcess(this._blurX);
  64228. this._blurX.dispose();
  64229. this._blurX = null;
  64230. }
  64231. }
  64232. };
  64233. MirrorTexture.prototype.clone = function () {
  64234. var scene = this.getScene();
  64235. if (!scene) {
  64236. return this;
  64237. }
  64238. var textureSize = this.getSize();
  64239. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64240. // Base texture
  64241. newTexture.hasAlpha = this.hasAlpha;
  64242. newTexture.level = this.level;
  64243. // Mirror Texture
  64244. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64245. if (this.renderList) {
  64246. newTexture.renderList = this.renderList.slice(0);
  64247. }
  64248. return newTexture;
  64249. };
  64250. MirrorTexture.prototype.serialize = function () {
  64251. if (!this.name) {
  64252. return null;
  64253. }
  64254. var serializationObject = _super.prototype.serialize.call(this);
  64255. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64256. return serializationObject;
  64257. };
  64258. MirrorTexture.prototype.dispose = function () {
  64259. _super.prototype.dispose.call(this);
  64260. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64261. };
  64262. return MirrorTexture;
  64263. }(BABYLON.RenderTargetTexture));
  64264. BABYLON.MirrorTexture = MirrorTexture;
  64265. })(BABYLON || (BABYLON = {}));
  64266. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64267. var BABYLON;
  64268. (function (BABYLON) {
  64269. /**
  64270. * Creates a refraction texture used by refraction channel of the standard material.
  64271. * @param name the texture name
  64272. * @param size size of the underlying texture
  64273. * @param scene root scene
  64274. */
  64275. var RefractionTexture = /** @class */ (function (_super) {
  64276. __extends(RefractionTexture, _super);
  64277. function RefractionTexture(name, size, scene, generateMipMaps) {
  64278. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64279. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64280. _this.depth = 2.0;
  64281. _this.onBeforeRenderObservable.add(function () {
  64282. scene.clipPlane = _this.refractionPlane;
  64283. });
  64284. _this.onAfterRenderObservable.add(function () {
  64285. delete scene.clipPlane;
  64286. });
  64287. return _this;
  64288. }
  64289. RefractionTexture.prototype.clone = function () {
  64290. var scene = this.getScene();
  64291. if (!scene) {
  64292. return this;
  64293. }
  64294. var textureSize = this.getSize();
  64295. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64296. // Base texture
  64297. newTexture.hasAlpha = this.hasAlpha;
  64298. newTexture.level = this.level;
  64299. // Refraction Texture
  64300. newTexture.refractionPlane = this.refractionPlane.clone();
  64301. if (this.renderList) {
  64302. newTexture.renderList = this.renderList.slice(0);
  64303. }
  64304. newTexture.depth = this.depth;
  64305. return newTexture;
  64306. };
  64307. RefractionTexture.prototype.serialize = function () {
  64308. if (!this.name) {
  64309. return null;
  64310. }
  64311. var serializationObject = _super.prototype.serialize.call(this);
  64312. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64313. serializationObject.depth = this.depth;
  64314. return serializationObject;
  64315. };
  64316. return RefractionTexture;
  64317. }(BABYLON.RenderTargetTexture));
  64318. BABYLON.RefractionTexture = RefractionTexture;
  64319. })(BABYLON || (BABYLON = {}));
  64320. //# sourceMappingURL=babylon.refractionTexture.js.map
  64321. var BABYLON;
  64322. (function (BABYLON) {
  64323. /**
  64324. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64325. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64326. */
  64327. var DynamicTexture = /** @class */ (function (_super) {
  64328. __extends(DynamicTexture, _super);
  64329. /**
  64330. * Creates a {BABYLON.DynamicTexture}
  64331. * @param name defines the name of the texture
  64332. * @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
  64333. * @param scene defines the scene where you want the texture
  64334. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64335. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64336. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64337. */
  64338. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64339. if (scene === void 0) { scene = null; }
  64340. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64341. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64342. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64343. _this.name = name;
  64344. _this._engine = _this.getScene().getEngine();
  64345. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64346. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64347. _this._generateMipMaps = generateMipMaps;
  64348. if (options.getContext) {
  64349. _this._canvas = options;
  64350. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64351. }
  64352. else {
  64353. _this._canvas = document.createElement("canvas");
  64354. if (options.width || options.width === 0) {
  64355. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64356. }
  64357. else {
  64358. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64359. }
  64360. }
  64361. var textureSize = _this.getSize();
  64362. _this._canvas.width = textureSize.width;
  64363. _this._canvas.height = textureSize.height;
  64364. _this._context = _this._canvas.getContext("2d");
  64365. return _this;
  64366. }
  64367. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64368. /**
  64369. * Gets the current state of canRescale
  64370. */
  64371. get: function () {
  64372. return true;
  64373. },
  64374. enumerable: true,
  64375. configurable: true
  64376. });
  64377. DynamicTexture.prototype._recreate = function (textureSize) {
  64378. this._canvas.width = textureSize.width;
  64379. this._canvas.height = textureSize.height;
  64380. this.releaseInternalTexture();
  64381. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64382. };
  64383. /**
  64384. * Scales the texture
  64385. * @param ratio the scale factor to apply to both width and height
  64386. */
  64387. DynamicTexture.prototype.scale = function (ratio) {
  64388. var textureSize = this.getSize();
  64389. textureSize.width *= ratio;
  64390. textureSize.height *= ratio;
  64391. this._recreate(textureSize);
  64392. };
  64393. /**
  64394. * Resizes the texture
  64395. * @param width the new width
  64396. * @param height the new height
  64397. */
  64398. DynamicTexture.prototype.scaleTo = function (width, height) {
  64399. var textureSize = this.getSize();
  64400. textureSize.width = width;
  64401. textureSize.height = height;
  64402. this._recreate(textureSize);
  64403. };
  64404. /**
  64405. * Gets the context of the canvas used by the texture
  64406. * @returns the canvas context of the dynamic texture
  64407. */
  64408. DynamicTexture.prototype.getContext = function () {
  64409. return this._context;
  64410. };
  64411. /**
  64412. * Clears the texture
  64413. */
  64414. DynamicTexture.prototype.clear = function () {
  64415. var size = this.getSize();
  64416. this._context.fillRect(0, 0, size.width, size.height);
  64417. };
  64418. /**
  64419. * Updates the texture
  64420. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64421. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64422. */
  64423. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64424. if (premulAlpha === void 0) { premulAlpha = false; }
  64425. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64426. };
  64427. /**
  64428. * Draws text onto the texture
  64429. * @param text defines the text to be drawn
  64430. * @param x defines the placement of the text from the left
  64431. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64432. * @param font defines the font to be used with font-style, font-size, font-name
  64433. * @param color defines the color used for the text
  64434. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64435. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64436. * @param update defines whether texture is immediately update (default is true)
  64437. */
  64438. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64439. if (update === void 0) { update = true; }
  64440. var size = this.getSize();
  64441. if (clearColor) {
  64442. this._context.fillStyle = clearColor;
  64443. this._context.fillRect(0, 0, size.width, size.height);
  64444. }
  64445. this._context.font = font;
  64446. if (x === null || x === undefined) {
  64447. var textSize = this._context.measureText(text);
  64448. x = (size.width - textSize.width) / 2;
  64449. }
  64450. if (y === null || y === undefined) {
  64451. var fontSize = parseInt((font.replace(/\D/g, '')));
  64452. y = (size.height / 2) + (fontSize / 3.65);
  64453. }
  64454. this._context.fillStyle = color;
  64455. this._context.fillText(text, x, y);
  64456. if (update) {
  64457. this.update(invertY);
  64458. }
  64459. };
  64460. /**
  64461. * Clones the texture
  64462. * @returns the clone of the texture.
  64463. */
  64464. DynamicTexture.prototype.clone = function () {
  64465. var scene = this.getScene();
  64466. if (!scene) {
  64467. return this;
  64468. }
  64469. var textureSize = this.getSize();
  64470. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64471. // Base texture
  64472. newTexture.hasAlpha = this.hasAlpha;
  64473. newTexture.level = this.level;
  64474. // Dynamic Texture
  64475. newTexture.wrapU = this.wrapU;
  64476. newTexture.wrapV = this.wrapV;
  64477. return newTexture;
  64478. };
  64479. /** @hidden */
  64480. DynamicTexture.prototype._rebuild = function () {
  64481. this.update();
  64482. };
  64483. return DynamicTexture;
  64484. }(BABYLON.Texture));
  64485. BABYLON.DynamicTexture = DynamicTexture;
  64486. })(BABYLON || (BABYLON = {}));
  64487. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64488. var BABYLON;
  64489. (function (BABYLON) {
  64490. var VideoTexture = /** @class */ (function (_super) {
  64491. __extends(VideoTexture, _super);
  64492. /**
  64493. * Creates a video texture.
  64494. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64495. * @param {string | null} name optional name, will detect from video source, if not defined
  64496. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64497. * @param {BABYLON.Scene} scene is obviously the current scene.
  64498. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64499. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64500. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64501. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64502. */
  64503. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64504. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64505. if (invertY === void 0) { invertY = false; }
  64506. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64507. if (settings === void 0) { settings = {
  64508. autoPlay: true,
  64509. loop: true,
  64510. autoUpdateTexture: true,
  64511. }; }
  64512. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64513. _this._onUserActionRequestedObservable = null;
  64514. _this._stillImageCaptured = false;
  64515. _this._createInternalTexture = function () {
  64516. if (_this._texture != null) {
  64517. return;
  64518. }
  64519. if (!_this._engine.needPOTTextures ||
  64520. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64521. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64522. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64523. }
  64524. else {
  64525. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64526. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64527. _this._generateMipMaps = false;
  64528. }
  64529. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64530. if (!_this.video.autoplay) {
  64531. var oldHandler_1 = _this.video.onplaying;
  64532. var error_1 = false;
  64533. _this.video.onplaying = function () {
  64534. _this.video.onplaying = oldHandler_1;
  64535. _this._texture.isReady = true;
  64536. _this._updateInternalTexture();
  64537. if (!error_1) {
  64538. _this.video.pause();
  64539. }
  64540. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64541. _this.onLoadObservable.notifyObservers(_this);
  64542. }
  64543. };
  64544. var playing = _this.video.play();
  64545. if (playing) {
  64546. playing.then(function () {
  64547. // Everything is good.
  64548. })
  64549. .catch(function () {
  64550. error_1 = true;
  64551. // On Chrome for instance, new policies might prevent playing without user interaction.
  64552. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64553. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64554. }
  64555. });
  64556. }
  64557. else {
  64558. _this.video.onplaying = oldHandler_1;
  64559. _this._texture.isReady = true;
  64560. _this._updateInternalTexture();
  64561. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64562. _this.onLoadObservable.notifyObservers(_this);
  64563. }
  64564. }
  64565. }
  64566. else {
  64567. _this._texture.isReady = true;
  64568. _this._updateInternalTexture();
  64569. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64570. _this.onLoadObservable.notifyObservers(_this);
  64571. }
  64572. }
  64573. };
  64574. _this.reset = function () {
  64575. if (_this._texture == null) {
  64576. return;
  64577. }
  64578. _this._texture.dispose();
  64579. _this._texture = null;
  64580. };
  64581. _this._updateInternalTexture = function (e) {
  64582. if (_this._texture == null || !_this._texture.isReady) {
  64583. return;
  64584. }
  64585. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64586. return;
  64587. }
  64588. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64589. };
  64590. _this._engine = _this.getScene().getEngine();
  64591. _this._generateMipMaps = generateMipMaps;
  64592. _this._samplingMode = samplingMode;
  64593. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64594. _this.name = name || _this._getName(src);
  64595. _this.video = _this._getVideo(src);
  64596. if (settings.poster) {
  64597. _this.video.poster = settings.poster;
  64598. }
  64599. if (settings.autoPlay !== undefined) {
  64600. _this.video.autoplay = settings.autoPlay;
  64601. }
  64602. if (settings.loop !== undefined) {
  64603. _this.video.loop = settings.loop;
  64604. }
  64605. _this.video.setAttribute("playsinline", "");
  64606. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64607. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64608. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64609. _this.video.addEventListener("emptied", _this.reset);
  64610. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64611. _this._createInternalTexture();
  64612. }
  64613. return _this;
  64614. }
  64615. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64616. get: function () {
  64617. if (!this._onUserActionRequestedObservable) {
  64618. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64619. }
  64620. return this._onUserActionRequestedObservable;
  64621. },
  64622. enumerable: true,
  64623. configurable: true
  64624. });
  64625. VideoTexture.prototype._getName = function (src) {
  64626. if (src instanceof HTMLVideoElement) {
  64627. return src.currentSrc;
  64628. }
  64629. if (typeof src === "object") {
  64630. return src.toString();
  64631. }
  64632. return src;
  64633. };
  64634. ;
  64635. VideoTexture.prototype._getVideo = function (src) {
  64636. if (src instanceof HTMLVideoElement) {
  64637. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64638. return src;
  64639. }
  64640. var video = document.createElement("video");
  64641. if (typeof src === "string") {
  64642. BABYLON.Tools.SetCorsBehavior(src, video);
  64643. video.src = src;
  64644. }
  64645. else {
  64646. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64647. src.forEach(function (url) {
  64648. var source = document.createElement("source");
  64649. source.src = url;
  64650. video.appendChild(source);
  64651. });
  64652. }
  64653. return video;
  64654. };
  64655. ;
  64656. /**
  64657. * Internal method to initiate `update`.
  64658. */
  64659. VideoTexture.prototype._rebuild = function () {
  64660. this.update();
  64661. };
  64662. /**
  64663. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64664. */
  64665. VideoTexture.prototype.update = function () {
  64666. if (!this.autoUpdateTexture) {
  64667. // Expecting user to call `updateTexture` manually
  64668. return;
  64669. }
  64670. this.updateTexture(true);
  64671. };
  64672. /**
  64673. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64674. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64675. */
  64676. VideoTexture.prototype.updateTexture = function (isVisible) {
  64677. if (!isVisible) {
  64678. return;
  64679. }
  64680. if (this.video.paused && this._stillImageCaptured) {
  64681. return;
  64682. }
  64683. this._stillImageCaptured = true;
  64684. this._updateInternalTexture();
  64685. };
  64686. /**
  64687. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64688. * @param url New url.
  64689. */
  64690. VideoTexture.prototype.updateURL = function (url) {
  64691. this.video.src = url;
  64692. };
  64693. VideoTexture.prototype.dispose = function () {
  64694. _super.prototype.dispose.call(this);
  64695. if (this._onUserActionRequestedObservable) {
  64696. this._onUserActionRequestedObservable.clear();
  64697. this._onUserActionRequestedObservable = null;
  64698. }
  64699. this.video.removeEventListener("canplay", this._createInternalTexture);
  64700. this.video.removeEventListener("paused", this._updateInternalTexture);
  64701. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64702. this.video.removeEventListener("emptied", this.reset);
  64703. this.video.pause();
  64704. };
  64705. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64706. var video = document.createElement("video");
  64707. video.setAttribute('autoplay', '');
  64708. video.setAttribute('muted', '');
  64709. video.setAttribute('playsinline', '');
  64710. var constraintsDeviceId;
  64711. if (constraints && constraints.deviceId) {
  64712. constraintsDeviceId = {
  64713. exact: constraints.deviceId,
  64714. };
  64715. }
  64716. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64717. if (navigator.mediaDevices) {
  64718. navigator.mediaDevices.getUserMedia({ video: constraints })
  64719. .then(function (stream) {
  64720. if (video.mozSrcObject !== undefined) {
  64721. // hack for Firefox < 19
  64722. video.mozSrcObject = stream;
  64723. }
  64724. else {
  64725. video.srcObject = stream;
  64726. }
  64727. var onPlaying = function () {
  64728. if (onReady) {
  64729. onReady(new VideoTexture("video", video, scene, true, true));
  64730. }
  64731. video.removeEventListener("playing", onPlaying);
  64732. };
  64733. video.addEventListener("playing", onPlaying);
  64734. video.play();
  64735. })
  64736. .catch(function (err) {
  64737. BABYLON.Tools.Error(err.name);
  64738. });
  64739. }
  64740. else {
  64741. navigator.getUserMedia =
  64742. navigator.getUserMedia ||
  64743. navigator.webkitGetUserMedia ||
  64744. navigator.mozGetUserMedia ||
  64745. navigator.msGetUserMedia;
  64746. if (navigator.getUserMedia) {
  64747. navigator.getUserMedia({
  64748. video: {
  64749. deviceId: constraintsDeviceId,
  64750. width: {
  64751. min: (constraints && constraints.minWidth) || 256,
  64752. max: (constraints && constraints.maxWidth) || 640,
  64753. },
  64754. height: {
  64755. min: (constraints && constraints.minHeight) || 256,
  64756. max: (constraints && constraints.maxHeight) || 480,
  64757. },
  64758. },
  64759. }, function (stream) {
  64760. if (video.mozSrcObject !== undefined) {
  64761. // hack for Firefox < 19
  64762. video.mozSrcObject = stream;
  64763. }
  64764. else {
  64765. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64766. }
  64767. video.play();
  64768. if (onReady) {
  64769. onReady(new VideoTexture("video", video, scene, true, true));
  64770. }
  64771. }, function (e) {
  64772. BABYLON.Tools.Error(e.name);
  64773. });
  64774. }
  64775. }
  64776. };
  64777. return VideoTexture;
  64778. }(BABYLON.Texture));
  64779. BABYLON.VideoTexture = VideoTexture;
  64780. })(BABYLON || (BABYLON = {}));
  64781. //# sourceMappingURL=babylon.videoTexture.js.map
  64782. var BABYLON;
  64783. (function (BABYLON) {
  64784. var RawTexture = /** @class */ (function (_super) {
  64785. __extends(RawTexture, _super);
  64786. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64787. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64788. if (invertY === void 0) { invertY = false; }
  64789. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64790. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64791. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64792. _this.format = format;
  64793. _this._engine = scene.getEngine();
  64794. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64795. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64796. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64797. return _this;
  64798. }
  64799. RawTexture.prototype.update = function (data) {
  64800. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64801. };
  64802. // Statics
  64803. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64804. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64805. if (invertY === void 0) { invertY = false; }
  64806. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64807. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64808. };
  64809. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64810. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64811. if (invertY === void 0) { invertY = false; }
  64812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64813. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64814. };
  64815. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64816. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64817. if (invertY === void 0) { invertY = false; }
  64818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64819. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64820. };
  64821. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64822. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64823. if (invertY === void 0) { invertY = false; }
  64824. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64825. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64826. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64827. };
  64828. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64829. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64830. if (invertY === void 0) { invertY = false; }
  64831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64832. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64833. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64834. };
  64835. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64836. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64837. if (invertY === void 0) { invertY = false; }
  64838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64839. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64840. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  64841. };
  64842. return RawTexture;
  64843. }(BABYLON.Texture));
  64844. BABYLON.RawTexture = RawTexture;
  64845. })(BABYLON || (BABYLON = {}));
  64846. //# sourceMappingURL=babylon.rawTexture.js.map
  64847. var BABYLON;
  64848. (function (BABYLON) {
  64849. /**
  64850. * Class used to store 3D textures containing user data
  64851. */
  64852. var RawTexture3D = /** @class */ (function (_super) {
  64853. __extends(RawTexture3D, _super);
  64854. /**
  64855. * Create a new RawTexture3D
  64856. * @param data defines the data of the texture
  64857. * @param width defines the width of the texture
  64858. * @param height defines the height of the texture
  64859. * @param depth defines the depth of the texture
  64860. * @param format defines the texture format to use
  64861. * @param scene defines the hosting scene
  64862. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64863. * @param invertY defines if texture must be stored with Y axis inverted
  64864. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64865. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64866. */
  64867. function RawTexture3D(data, width, height, depth,
  64868. /** Gets or sets the texture format to use */
  64869. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64870. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64871. if (invertY === void 0) { invertY = false; }
  64872. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64873. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64874. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64875. _this.format = format;
  64876. _this._engine = scene.getEngine();
  64877. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64878. _this.is3D = true;
  64879. return _this;
  64880. }
  64881. /**
  64882. * Update the texture with new data
  64883. * @param data defines the data to store in the texture
  64884. */
  64885. RawTexture3D.prototype.update = function (data) {
  64886. if (!this._texture) {
  64887. return;
  64888. }
  64889. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64890. };
  64891. return RawTexture3D;
  64892. }(BABYLON.Texture));
  64893. BABYLON.RawTexture3D = RawTexture3D;
  64894. })(BABYLON || (BABYLON = {}));
  64895. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64896. var BABYLON;
  64897. (function (BABYLON) {
  64898. /**
  64899. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64900. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64901. */
  64902. var PostProcessManager = /** @class */ (function () {
  64903. /**
  64904. * Creates a new instance PostProcess
  64905. * @param scene The scene that the post process is associated with.
  64906. */
  64907. function PostProcessManager(scene) {
  64908. this._vertexBuffers = {};
  64909. this._scene = scene;
  64910. }
  64911. PostProcessManager.prototype._prepareBuffers = function () {
  64912. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64913. return;
  64914. }
  64915. // VBO
  64916. var vertices = [];
  64917. vertices.push(1, 1);
  64918. vertices.push(-1, 1);
  64919. vertices.push(-1, -1);
  64920. vertices.push(1, -1);
  64921. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64922. this._buildIndexBuffer();
  64923. };
  64924. PostProcessManager.prototype._buildIndexBuffer = function () {
  64925. // Indices
  64926. var indices = [];
  64927. indices.push(0);
  64928. indices.push(1);
  64929. indices.push(2);
  64930. indices.push(0);
  64931. indices.push(2);
  64932. indices.push(3);
  64933. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64934. };
  64935. /**
  64936. * Rebuilds the vertex buffers of the manager.
  64937. */
  64938. PostProcessManager.prototype._rebuild = function () {
  64939. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64940. if (!vb) {
  64941. return;
  64942. }
  64943. vb._rebuild();
  64944. this._buildIndexBuffer();
  64945. };
  64946. // Methods
  64947. /**
  64948. * Prepares a frame to be run through a post process.
  64949. * @param sourceTexture The input texture to the post procesess. (default: null)
  64950. * @param postProcesses An array of post processes to be run. (default: null)
  64951. * @returns True if the post processes were able to be run.
  64952. */
  64953. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64954. if (sourceTexture === void 0) { sourceTexture = null; }
  64955. if (postProcesses === void 0) { postProcesses = null; }
  64956. var camera = this._scene.activeCamera;
  64957. if (!camera) {
  64958. return false;
  64959. }
  64960. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64961. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64962. return false;
  64963. }
  64964. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64965. return true;
  64966. };
  64967. /**
  64968. * Manually render a set of post processes to a texture.
  64969. * @param postProcesses An array of post processes to be run.
  64970. * @param targetTexture The target texture to render to.
  64971. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64972. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  64973. * @param lodLevel defines which lod of the texture to render to
  64974. */
  64975. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  64976. if (targetTexture === void 0) { targetTexture = null; }
  64977. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64978. if (faceIndex === void 0) { faceIndex = 0; }
  64979. if (lodLevel === void 0) { lodLevel = 0; }
  64980. var engine = this._scene.getEngine();
  64981. for (var index = 0; index < postProcesses.length; index++) {
  64982. if (index < postProcesses.length - 1) {
  64983. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  64984. }
  64985. else {
  64986. if (targetTexture) {
  64987. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  64988. }
  64989. else {
  64990. engine.restoreDefaultFramebuffer();
  64991. }
  64992. }
  64993. var pp = postProcesses[index];
  64994. var effect = pp.apply();
  64995. if (effect) {
  64996. pp.onBeforeRenderObservable.notifyObservers(effect);
  64997. // VBOs
  64998. this._prepareBuffers();
  64999. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65000. // Draw order
  65001. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65002. pp.onAfterRenderObservable.notifyObservers(effect);
  65003. }
  65004. }
  65005. // Restore depth buffer
  65006. engine.setDepthBuffer(true);
  65007. engine.setDepthWrite(true);
  65008. };
  65009. /**
  65010. * Finalize the result of the output of the postprocesses.
  65011. * @param doNotPresent If true the result will not be displayed to the screen.
  65012. * @param targetTexture The target texture to render to.
  65013. * @param faceIndex The index of the face to bind the target texture to.
  65014. * @param postProcesses The array of post processes to render.
  65015. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65016. */
  65017. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65018. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65019. var camera = this._scene.activeCamera;
  65020. if (!camera) {
  65021. return;
  65022. }
  65023. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65024. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65025. return;
  65026. }
  65027. var engine = this._scene.getEngine();
  65028. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65029. var pp = postProcesses[index];
  65030. if (index < len - 1) {
  65031. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65032. }
  65033. else {
  65034. if (targetTexture) {
  65035. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65036. pp._outputTexture = targetTexture;
  65037. }
  65038. else {
  65039. engine.restoreDefaultFramebuffer();
  65040. pp._outputTexture = null;
  65041. }
  65042. }
  65043. if (doNotPresent) {
  65044. break;
  65045. }
  65046. var effect = pp.apply();
  65047. if (effect) {
  65048. pp.onBeforeRenderObservable.notifyObservers(effect);
  65049. // VBOs
  65050. this._prepareBuffers();
  65051. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65052. // Draw order
  65053. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65054. pp.onAfterRenderObservable.notifyObservers(effect);
  65055. }
  65056. }
  65057. // Restore states
  65058. engine.setDepthBuffer(true);
  65059. engine.setDepthWrite(true);
  65060. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65061. };
  65062. /**
  65063. * Disposes of the post process manager.
  65064. */
  65065. PostProcessManager.prototype.dispose = function () {
  65066. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65067. if (buffer) {
  65068. buffer.dispose();
  65069. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65070. }
  65071. if (this._indexBuffer) {
  65072. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65073. this._indexBuffer = null;
  65074. }
  65075. };
  65076. return PostProcessManager;
  65077. }());
  65078. BABYLON.PostProcessManager = PostProcessManager;
  65079. })(BABYLON || (BABYLON = {}));
  65080. //# sourceMappingURL=babylon.postProcessManager.js.map
  65081. var BABYLON;
  65082. (function (BABYLON) {
  65083. /**
  65084. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65085. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65086. */
  65087. var PostProcess = /** @class */ (function () {
  65088. /**
  65089. * Creates a new instance PostProcess
  65090. * @param name The name of the PostProcess.
  65091. * @param fragmentUrl The url of the fragment shader to be used.
  65092. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65093. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65094. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65095. * @param camera The camera to apply the render pass to.
  65096. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65097. * @param engine The engine which the post process will be applied. (default: current engine)
  65098. * @param reusable If the post process can be reused on the same frame. (default: false)
  65099. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65100. * @param textureType Type of textures used when performing the post process. (default: 0)
  65101. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65102. * @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
  65103. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65104. */
  65105. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65106. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65107. if (defines === void 0) { defines = null; }
  65108. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65109. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65110. if (blockCompilation === void 0) { blockCompilation = false; }
  65111. this.name = name;
  65112. /**
  65113. * Width of the texture to apply the post process on
  65114. */
  65115. this.width = -1;
  65116. /**
  65117. * Height of the texture to apply the post process on
  65118. */
  65119. this.height = -1;
  65120. /**
  65121. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65122. */
  65123. this._outputTexture = null;
  65124. /**
  65125. * If the buffer needs to be cleared before applying the post process. (default: true)
  65126. * Should be set to false if shader will overwrite all previous pixels.
  65127. */
  65128. this.autoClear = true;
  65129. /**
  65130. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65131. */
  65132. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65133. /**
  65134. * Animations to be used for the post processing
  65135. */
  65136. this.animations = new Array();
  65137. /**
  65138. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65139. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65140. */
  65141. this.enablePixelPerfectMode = false;
  65142. /**
  65143. * Force the postprocess to be applied without taking in account viewport
  65144. */
  65145. this.forceFullscreenViewport = true;
  65146. /**
  65147. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65148. *
  65149. * | Value | Type | Description |
  65150. * | ----- | ----------------------------------- | ----------- |
  65151. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65152. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65153. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65154. *
  65155. */
  65156. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65157. /**
  65158. * Force textures to be a power of two (default: false)
  65159. */
  65160. this.alwaysForcePOT = false;
  65161. /**
  65162. * Number of sample textures (default: 1)
  65163. */
  65164. this.samples = 1;
  65165. /**
  65166. * Modify the scale of the post process to be the same as the viewport (default: false)
  65167. */
  65168. this.adaptScaleToCurrentViewport = false;
  65169. this._reusable = false;
  65170. /**
  65171. * Smart array of input and output textures for the post process.
  65172. */
  65173. this._textures = new BABYLON.SmartArray(2);
  65174. /**
  65175. * The index in _textures that corresponds to the output texture.
  65176. */
  65177. this._currentRenderTextureInd = 0;
  65178. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65179. this._texelSize = BABYLON.Vector2.Zero();
  65180. // Events
  65181. /**
  65182. * An event triggered when the postprocess is activated.
  65183. */
  65184. this.onActivateObservable = new BABYLON.Observable();
  65185. /**
  65186. * An event triggered when the postprocess changes its size.
  65187. */
  65188. this.onSizeChangedObservable = new BABYLON.Observable();
  65189. /**
  65190. * An event triggered when the postprocess applies its effect.
  65191. */
  65192. this.onApplyObservable = new BABYLON.Observable();
  65193. /**
  65194. * An event triggered before rendering the postprocess
  65195. */
  65196. this.onBeforeRenderObservable = new BABYLON.Observable();
  65197. /**
  65198. * An event triggered after rendering the postprocess
  65199. */
  65200. this.onAfterRenderObservable = new BABYLON.Observable();
  65201. if (camera != null) {
  65202. this._camera = camera;
  65203. this._scene = camera.getScene();
  65204. camera.attachPostProcess(this);
  65205. this._engine = this._scene.getEngine();
  65206. this._scene.postProcesses.push(this);
  65207. }
  65208. else if (engine) {
  65209. this._engine = engine;
  65210. this._engine.postProcesses.push(this);
  65211. }
  65212. this._options = options;
  65213. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65214. this._reusable = reusable || false;
  65215. this._textureType = textureType;
  65216. this._samplers = samplers || [];
  65217. this._samplers.push("textureSampler");
  65218. this._fragmentUrl = fragmentUrl;
  65219. this._vertexUrl = vertexUrl;
  65220. this._parameters = parameters || [];
  65221. this._parameters.push("scale");
  65222. this._indexParameters = indexParameters;
  65223. if (!blockCompilation) {
  65224. this.updateEffect(defines);
  65225. }
  65226. }
  65227. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65228. /**
  65229. * A function that is added to the onActivateObservable
  65230. */
  65231. set: function (callback) {
  65232. if (this._onActivateObserver) {
  65233. this.onActivateObservable.remove(this._onActivateObserver);
  65234. }
  65235. if (callback) {
  65236. this._onActivateObserver = this.onActivateObservable.add(callback);
  65237. }
  65238. },
  65239. enumerable: true,
  65240. configurable: true
  65241. });
  65242. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65243. /**
  65244. * A function that is added to the onSizeChangedObservable
  65245. */
  65246. set: function (callback) {
  65247. if (this._onSizeChangedObserver) {
  65248. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65249. }
  65250. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65251. },
  65252. enumerable: true,
  65253. configurable: true
  65254. });
  65255. Object.defineProperty(PostProcess.prototype, "onApply", {
  65256. /**
  65257. * A function that is added to the onApplyObservable
  65258. */
  65259. set: function (callback) {
  65260. if (this._onApplyObserver) {
  65261. this.onApplyObservable.remove(this._onApplyObserver);
  65262. }
  65263. this._onApplyObserver = this.onApplyObservable.add(callback);
  65264. },
  65265. enumerable: true,
  65266. configurable: true
  65267. });
  65268. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65269. /**
  65270. * A function that is added to the onBeforeRenderObservable
  65271. */
  65272. set: function (callback) {
  65273. if (this._onBeforeRenderObserver) {
  65274. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65275. }
  65276. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65277. },
  65278. enumerable: true,
  65279. configurable: true
  65280. });
  65281. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65282. /**
  65283. * A function that is added to the onAfterRenderObservable
  65284. */
  65285. set: function (callback) {
  65286. if (this._onAfterRenderObserver) {
  65287. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65288. }
  65289. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65290. },
  65291. enumerable: true,
  65292. configurable: true
  65293. });
  65294. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65295. /**
  65296. * 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
  65297. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65298. */
  65299. get: function () {
  65300. return this._textures.data[this._currentRenderTextureInd];
  65301. },
  65302. set: function (value) {
  65303. this._forcedOutputTexture = value;
  65304. },
  65305. enumerable: true,
  65306. configurable: true
  65307. });
  65308. /**
  65309. * Gets the camera which post process is applied to.
  65310. * @returns The camera the post process is applied to.
  65311. */
  65312. PostProcess.prototype.getCamera = function () {
  65313. return this._camera;
  65314. };
  65315. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65316. /**
  65317. * Gets the texel size of the postprocess.
  65318. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65319. */
  65320. get: function () {
  65321. if (this._shareOutputWithPostProcess) {
  65322. return this._shareOutputWithPostProcess.texelSize;
  65323. }
  65324. if (this._forcedOutputTexture) {
  65325. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65326. }
  65327. return this._texelSize;
  65328. },
  65329. enumerable: true,
  65330. configurable: true
  65331. });
  65332. /**
  65333. * Gets the engine which this post process belongs to.
  65334. * @returns The engine the post process was enabled with.
  65335. */
  65336. PostProcess.prototype.getEngine = function () {
  65337. return this._engine;
  65338. };
  65339. /**
  65340. * The effect that is created when initializing the post process.
  65341. * @returns The created effect corrisponding the the postprocess.
  65342. */
  65343. PostProcess.prototype.getEffect = function () {
  65344. return this._effect;
  65345. };
  65346. /**
  65347. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65348. * @param postProcess The post process to share the output with.
  65349. * @returns This post process.
  65350. */
  65351. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65352. this._disposeTextures();
  65353. this._shareOutputWithPostProcess = postProcess;
  65354. return this;
  65355. };
  65356. /**
  65357. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65358. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65359. */
  65360. PostProcess.prototype.useOwnOutput = function () {
  65361. if (this._textures.length == 0) {
  65362. this._textures = new BABYLON.SmartArray(2);
  65363. }
  65364. this._shareOutputWithPostProcess = null;
  65365. };
  65366. /**
  65367. * Updates the effect with the current post process compile time values and recompiles the shader.
  65368. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65369. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65370. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65371. * @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
  65372. * @param onCompiled Called when the shader has been compiled.
  65373. * @param onError Called if there is an error when compiling a shader.
  65374. */
  65375. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65376. if (defines === void 0) { defines = null; }
  65377. if (uniforms === void 0) { uniforms = null; }
  65378. if (samplers === void 0) { samplers = null; }
  65379. 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);
  65380. };
  65381. /**
  65382. * The post process is reusable if it can be used multiple times within one frame.
  65383. * @returns If the post process is reusable
  65384. */
  65385. PostProcess.prototype.isReusable = function () {
  65386. return this._reusable;
  65387. };
  65388. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65389. PostProcess.prototype.markTextureDirty = function () {
  65390. this.width = -1;
  65391. };
  65392. /**
  65393. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65394. * 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.
  65395. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65396. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65397. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65398. * @returns The target texture that was bound to be written to.
  65399. */
  65400. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65401. var _this = this;
  65402. if (sourceTexture === void 0) { sourceTexture = null; }
  65403. camera = camera || this._camera;
  65404. var scene = camera.getScene();
  65405. var engine = scene.getEngine();
  65406. var maxSize = engine.getCaps().maxTextureSize;
  65407. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65408. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65409. // 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
  65410. var webVRCamera = camera.parent;
  65411. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65412. requiredWidth /= 2;
  65413. }
  65414. var desiredWidth = (this._options.width || requiredWidth);
  65415. var desiredHeight = this._options.height || requiredHeight;
  65416. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65417. if (this.adaptScaleToCurrentViewport) {
  65418. var currentViewport = engine.currentViewport;
  65419. if (currentViewport) {
  65420. desiredWidth *= currentViewport.width;
  65421. desiredHeight *= currentViewport.height;
  65422. }
  65423. }
  65424. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65425. if (!this._options.width) {
  65426. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65427. }
  65428. if (!this._options.height) {
  65429. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65430. }
  65431. }
  65432. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65433. if (this._textures.length > 0) {
  65434. for (var i = 0; i < this._textures.length; i++) {
  65435. this._engine._releaseTexture(this._textures.data[i]);
  65436. }
  65437. this._textures.reset();
  65438. }
  65439. this.width = desiredWidth;
  65440. this.height = desiredHeight;
  65441. var textureSize = { width: this.width, height: this.height };
  65442. var textureOptions = {
  65443. generateMipMaps: false,
  65444. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65445. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65446. samplingMode: this.renderTargetSamplingMode,
  65447. type: this._textureType
  65448. };
  65449. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65450. if (this._reusable) {
  65451. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65452. }
  65453. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65454. this.onSizeChangedObservable.notifyObservers(this);
  65455. }
  65456. this._textures.forEach(function (texture) {
  65457. if (texture.samples !== _this.samples) {
  65458. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65459. }
  65460. });
  65461. }
  65462. var target;
  65463. if (this._shareOutputWithPostProcess) {
  65464. target = this._shareOutputWithPostProcess.inputTexture;
  65465. }
  65466. else if (this._forcedOutputTexture) {
  65467. target = this._forcedOutputTexture;
  65468. this.width = this._forcedOutputTexture.width;
  65469. this.height = this._forcedOutputTexture.height;
  65470. }
  65471. else {
  65472. target = this.inputTexture;
  65473. }
  65474. // Bind the input of this post process to be used as the output of the previous post process.
  65475. if (this.enablePixelPerfectMode) {
  65476. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65477. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65478. }
  65479. else {
  65480. this._scaleRatio.copyFromFloats(1, 1);
  65481. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65482. }
  65483. this.onActivateObservable.notifyObservers(camera);
  65484. // Clear
  65485. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65486. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65487. }
  65488. if (this._reusable) {
  65489. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65490. }
  65491. return target;
  65492. };
  65493. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65494. /**
  65495. * If the post process is supported.
  65496. */
  65497. get: function () {
  65498. return this._effect.isSupported;
  65499. },
  65500. enumerable: true,
  65501. configurable: true
  65502. });
  65503. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65504. /**
  65505. * The aspect ratio of the output texture.
  65506. */
  65507. get: function () {
  65508. if (this._shareOutputWithPostProcess) {
  65509. return this._shareOutputWithPostProcess.aspectRatio;
  65510. }
  65511. if (this._forcedOutputTexture) {
  65512. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65513. }
  65514. return this.width / this.height;
  65515. },
  65516. enumerable: true,
  65517. configurable: true
  65518. });
  65519. /**
  65520. * Get a value indicating if the post-process is ready to be used
  65521. * @returns true if the post-process is ready (shader is compiled)
  65522. */
  65523. PostProcess.prototype.isReady = function () {
  65524. return this._effect && this._effect.isReady();
  65525. };
  65526. /**
  65527. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65528. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65529. */
  65530. PostProcess.prototype.apply = function () {
  65531. // Check
  65532. if (!this._effect || !this._effect.isReady())
  65533. return null;
  65534. // States
  65535. this._engine.enableEffect(this._effect);
  65536. this._engine.setState(false);
  65537. this._engine.setDepthBuffer(false);
  65538. this._engine.setDepthWrite(false);
  65539. // Alpha
  65540. this._engine.setAlphaMode(this.alphaMode);
  65541. if (this.alphaConstants) {
  65542. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65543. }
  65544. // Bind the output texture of the preivous post process as the input to this post process.
  65545. var source;
  65546. if (this._shareOutputWithPostProcess) {
  65547. source = this._shareOutputWithPostProcess.inputTexture;
  65548. }
  65549. else if (this._forcedOutputTexture) {
  65550. source = this._forcedOutputTexture;
  65551. }
  65552. else {
  65553. source = this.inputTexture;
  65554. }
  65555. this._effect._bindTexture("textureSampler", source);
  65556. // Parameters
  65557. this._effect.setVector2("scale", this._scaleRatio);
  65558. this.onApplyObservable.notifyObservers(this._effect);
  65559. return this._effect;
  65560. };
  65561. PostProcess.prototype._disposeTextures = function () {
  65562. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65563. return;
  65564. }
  65565. if (this._textures.length > 0) {
  65566. for (var i = 0; i < this._textures.length; i++) {
  65567. this._engine._releaseTexture(this._textures.data[i]);
  65568. }
  65569. }
  65570. this._textures.dispose();
  65571. };
  65572. /**
  65573. * Disposes the post process.
  65574. * @param camera The camera to dispose the post process on.
  65575. */
  65576. PostProcess.prototype.dispose = function (camera) {
  65577. camera = camera || this._camera;
  65578. this._disposeTextures();
  65579. if (this._scene) {
  65580. var index_1 = this._scene.postProcesses.indexOf(this);
  65581. if (index_1 !== -1) {
  65582. this._scene.postProcesses.splice(index_1, 1);
  65583. }
  65584. }
  65585. else {
  65586. var index_2 = this._engine.postProcesses.indexOf(this);
  65587. if (index_2 !== -1) {
  65588. this._engine.postProcesses.splice(index_2, 1);
  65589. }
  65590. }
  65591. if (!camera) {
  65592. return;
  65593. }
  65594. camera.detachPostProcess(this);
  65595. var index = camera._postProcesses.indexOf(this);
  65596. if (index === 0 && camera._postProcesses.length > 0) {
  65597. var firstPostProcess = this._camera._getFirstPostProcess();
  65598. if (firstPostProcess) {
  65599. firstPostProcess.markTextureDirty();
  65600. }
  65601. }
  65602. this.onActivateObservable.clear();
  65603. this.onAfterRenderObservable.clear();
  65604. this.onApplyObservable.clear();
  65605. this.onBeforeRenderObservable.clear();
  65606. this.onSizeChangedObservable.clear();
  65607. };
  65608. return PostProcess;
  65609. }());
  65610. BABYLON.PostProcess = PostProcess;
  65611. })(BABYLON || (BABYLON = {}));
  65612. //# sourceMappingURL=babylon.postProcess.js.map
  65613. var BABYLON;
  65614. (function (BABYLON) {
  65615. var PassPostProcess = /** @class */ (function (_super) {
  65616. __extends(PassPostProcess, _super);
  65617. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65618. if (camera === void 0) { camera = null; }
  65619. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65620. if (blockCompilation === void 0) { blockCompilation = false; }
  65621. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65622. }
  65623. return PassPostProcess;
  65624. }(BABYLON.PostProcess));
  65625. BABYLON.PassPostProcess = PassPostProcess;
  65626. })(BABYLON || (BABYLON = {}));
  65627. //# sourceMappingURL=babylon.passPostProcess.js.map
  65628. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65629. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65630. s = arguments[i];
  65631. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65632. t[p] = s[p];
  65633. }
  65634. return t;
  65635. };
  65636. var BABYLON;
  65637. (function (BABYLON) {
  65638. /**
  65639. * Default implementation IShadowGenerator.
  65640. * This is the main object responsible of generating shadows in the framework.
  65641. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65642. */
  65643. var ShadowGenerator = /** @class */ (function () {
  65644. /**
  65645. * Creates a ShadowGenerator object.
  65646. * A ShadowGenerator is the required tool to use the shadows.
  65647. * Each light casting shadows needs to use its own ShadowGenerator.
  65648. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65649. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65650. * @param light The light object generating the shadows.
  65651. * @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.
  65652. */
  65653. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65654. this._bias = 0.00005;
  65655. this._normalBias = 0;
  65656. this._blurBoxOffset = 1;
  65657. this._blurScale = 2;
  65658. this._blurKernel = 1;
  65659. this._useKernelBlur = false;
  65660. this._filter = ShadowGenerator.FILTER_NONE;
  65661. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65662. this._contactHardeningLightSizeUVRatio = 0.1;
  65663. this._darkness = 0;
  65664. this._transparencyShadow = false;
  65665. /**
  65666. * Controls the extent to which the shadows fade out at the edge of the frustum
  65667. * Used only by directionals and spots
  65668. */
  65669. this.frustumEdgeFalloff = 0;
  65670. /**
  65671. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65672. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65673. * It might on the other hand introduce peter panning.
  65674. */
  65675. this.forceBackFacesOnly = false;
  65676. this._lightDirection = BABYLON.Vector3.Zero();
  65677. this._viewMatrix = BABYLON.Matrix.Zero();
  65678. this._projectionMatrix = BABYLON.Matrix.Zero();
  65679. this._transformMatrix = BABYLON.Matrix.Zero();
  65680. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65681. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65682. this._currentFaceIndex = 0;
  65683. this._currentFaceIndexCache = 0;
  65684. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65685. this._mapSize = mapSize;
  65686. this._light = light;
  65687. this._scene = light.getScene();
  65688. light._shadowGenerator = this;
  65689. // Texture type fallback from float to int if not supported.
  65690. var caps = this._scene.getEngine().getCaps();
  65691. if (!useFullFloatFirst) {
  65692. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65693. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65694. }
  65695. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65696. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65697. }
  65698. else {
  65699. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65700. }
  65701. }
  65702. else {
  65703. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65704. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65705. }
  65706. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65707. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65708. }
  65709. else {
  65710. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65711. }
  65712. }
  65713. this._initializeGenerator();
  65714. this._applyFilterValues();
  65715. }
  65716. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65717. /**
  65718. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65719. */
  65720. get: function () {
  65721. return this._bias;
  65722. },
  65723. /**
  65724. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65725. */
  65726. set: function (bias) {
  65727. this._bias = bias;
  65728. },
  65729. enumerable: true,
  65730. configurable: true
  65731. });
  65732. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65733. /**
  65734. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65735. */
  65736. get: function () {
  65737. return this._normalBias;
  65738. },
  65739. /**
  65740. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65741. */
  65742. set: function (normalBias) {
  65743. this._normalBias = normalBias;
  65744. },
  65745. enumerable: true,
  65746. configurable: true
  65747. });
  65748. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65749. /**
  65750. * Gets the blur box offset: offset applied during the blur pass.
  65751. * Only usefull if useKernelBlur = false
  65752. */
  65753. get: function () {
  65754. return this._blurBoxOffset;
  65755. },
  65756. /**
  65757. * Sets the blur box offset: offset applied during the blur pass.
  65758. * Only usefull if useKernelBlur = false
  65759. */
  65760. set: function (value) {
  65761. if (this._blurBoxOffset === value) {
  65762. return;
  65763. }
  65764. this._blurBoxOffset = value;
  65765. this._disposeBlurPostProcesses();
  65766. },
  65767. enumerable: true,
  65768. configurable: true
  65769. });
  65770. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65771. /**
  65772. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65773. * 2 means half of the size.
  65774. */
  65775. get: function () {
  65776. return this._blurScale;
  65777. },
  65778. /**
  65779. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65780. * 2 means half of the size.
  65781. */
  65782. set: function (value) {
  65783. if (this._blurScale === value) {
  65784. return;
  65785. }
  65786. this._blurScale = value;
  65787. this._disposeBlurPostProcesses();
  65788. },
  65789. enumerable: true,
  65790. configurable: true
  65791. });
  65792. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65793. /**
  65794. * Gets the blur kernel: kernel size of the blur pass.
  65795. * Only usefull if useKernelBlur = true
  65796. */
  65797. get: function () {
  65798. return this._blurKernel;
  65799. },
  65800. /**
  65801. * Sets the blur kernel: kernel size of the blur pass.
  65802. * Only usefull if useKernelBlur = true
  65803. */
  65804. set: function (value) {
  65805. if (this._blurKernel === value) {
  65806. return;
  65807. }
  65808. this._blurKernel = value;
  65809. this._disposeBlurPostProcesses();
  65810. },
  65811. enumerable: true,
  65812. configurable: true
  65813. });
  65814. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65815. /**
  65816. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65817. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65818. */
  65819. get: function () {
  65820. return this._useKernelBlur;
  65821. },
  65822. /**
  65823. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65824. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65825. */
  65826. set: function (value) {
  65827. if (this._useKernelBlur === value) {
  65828. return;
  65829. }
  65830. this._useKernelBlur = value;
  65831. this._disposeBlurPostProcesses();
  65832. },
  65833. enumerable: true,
  65834. configurable: true
  65835. });
  65836. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65837. /**
  65838. * Gets the depth scale used in ESM mode.
  65839. */
  65840. get: function () {
  65841. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65842. },
  65843. /**
  65844. * Sets the depth scale used in ESM mode.
  65845. * This can override the scale stored on the light.
  65846. */
  65847. set: function (value) {
  65848. this._depthScale = value;
  65849. },
  65850. enumerable: true,
  65851. configurable: true
  65852. });
  65853. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65854. /**
  65855. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65856. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65857. */
  65858. get: function () {
  65859. return this._filter;
  65860. },
  65861. /**
  65862. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65863. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65864. */
  65865. set: function (value) {
  65866. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65867. if (this._light.needCube()) {
  65868. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65869. this.useExponentialShadowMap = true;
  65870. return;
  65871. }
  65872. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65873. this.useCloseExponentialShadowMap = true;
  65874. return;
  65875. }
  65876. // PCF on cubemap would also be expensive
  65877. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65878. this.usePoissonSampling = true;
  65879. return;
  65880. }
  65881. }
  65882. // Weblg1 fallback for PCF.
  65883. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65884. if (this._scene.getEngine().webGLVersion === 1) {
  65885. this.usePoissonSampling = true;
  65886. return;
  65887. }
  65888. }
  65889. if (this._filter === value) {
  65890. return;
  65891. }
  65892. this._filter = value;
  65893. this._disposeBlurPostProcesses();
  65894. this._applyFilterValues();
  65895. this._light._markMeshesAsLightDirty();
  65896. },
  65897. enumerable: true,
  65898. configurable: true
  65899. });
  65900. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65901. /**
  65902. * Gets if the current filter is set to Poisson Sampling.
  65903. */
  65904. get: function () {
  65905. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65906. },
  65907. /**
  65908. * Sets the current filter to Poisson Sampling.
  65909. */
  65910. set: function (value) {
  65911. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65912. return;
  65913. }
  65914. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65915. },
  65916. enumerable: true,
  65917. configurable: true
  65918. });
  65919. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65920. /**
  65921. * Gets if the current filter is set to VSM.
  65922. * DEPRECATED. Should use useExponentialShadowMap instead.
  65923. */
  65924. get: function () {
  65925. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65926. return this.useExponentialShadowMap;
  65927. },
  65928. /**
  65929. * Sets the current filter is to VSM.
  65930. * DEPRECATED. Should use useExponentialShadowMap instead.
  65931. */
  65932. set: function (value) {
  65933. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65934. this.useExponentialShadowMap = value;
  65935. },
  65936. enumerable: true,
  65937. configurable: true
  65938. });
  65939. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65940. /**
  65941. * Gets if the current filter is set to blurred VSM.
  65942. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65943. */
  65944. get: function () {
  65945. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65946. return this.useBlurExponentialShadowMap;
  65947. },
  65948. /**
  65949. * Sets the current filter is to blurred VSM.
  65950. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65951. */
  65952. set: function (value) {
  65953. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65954. this.useBlurExponentialShadowMap = value;
  65955. },
  65956. enumerable: true,
  65957. configurable: true
  65958. });
  65959. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65960. /**
  65961. * Gets if the current filter is set to ESM.
  65962. */
  65963. get: function () {
  65964. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65965. },
  65966. /**
  65967. * Sets the current filter is to ESM.
  65968. */
  65969. set: function (value) {
  65970. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65971. return;
  65972. }
  65973. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65974. },
  65975. enumerable: true,
  65976. configurable: true
  65977. });
  65978. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65979. /**
  65980. * Gets if the current filter is set to filtered ESM.
  65981. */
  65982. get: function () {
  65983. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65984. },
  65985. /**
  65986. * Gets if the current filter is set to filtered ESM.
  65987. */
  65988. set: function (value) {
  65989. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65990. return;
  65991. }
  65992. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65993. },
  65994. enumerable: true,
  65995. configurable: true
  65996. });
  65997. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65998. /**
  65999. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66000. * exponential to prevent steep falloff artifacts).
  66001. */
  66002. get: function () {
  66003. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66004. },
  66005. /**
  66006. * Sets the current filter to "close ESM" (using the inverse of the
  66007. * exponential to prevent steep falloff artifacts).
  66008. */
  66009. set: function (value) {
  66010. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66011. return;
  66012. }
  66013. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66014. },
  66015. enumerable: true,
  66016. configurable: true
  66017. });
  66018. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66019. /**
  66020. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66021. * exponential to prevent steep falloff artifacts).
  66022. */
  66023. get: function () {
  66024. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66025. },
  66026. /**
  66027. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66028. * exponential to prevent steep falloff artifacts).
  66029. */
  66030. set: function (value) {
  66031. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66032. return;
  66033. }
  66034. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66035. },
  66036. enumerable: true,
  66037. configurable: true
  66038. });
  66039. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66040. /**
  66041. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66042. */
  66043. get: function () {
  66044. return this.filter === ShadowGenerator.FILTER_PCF;
  66045. },
  66046. /**
  66047. * Sets the current filter to "PCF" (percentage closer filtering).
  66048. */
  66049. set: function (value) {
  66050. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66051. return;
  66052. }
  66053. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66054. },
  66055. enumerable: true,
  66056. configurable: true
  66057. });
  66058. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66059. /**
  66060. * Gets the PCF or PCSS Quality.
  66061. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66062. */
  66063. get: function () {
  66064. return this._filteringQuality;
  66065. },
  66066. /**
  66067. * Sets the PCF or PCSS Quality.
  66068. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66069. */
  66070. set: function (filteringQuality) {
  66071. this._filteringQuality = filteringQuality;
  66072. },
  66073. enumerable: true,
  66074. configurable: true
  66075. });
  66076. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66077. /**
  66078. * Gets if the current filter is set to "PCSS" (contact hardening).
  66079. */
  66080. get: function () {
  66081. return this.filter === ShadowGenerator.FILTER_PCSS;
  66082. },
  66083. /**
  66084. * Sets the current filter to "PCSS" (contact hardening).
  66085. */
  66086. set: function (value) {
  66087. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66088. return;
  66089. }
  66090. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66091. },
  66092. enumerable: true,
  66093. configurable: true
  66094. });
  66095. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66096. /**
  66097. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66098. * Using a ratio helps keeping shape stability independently of the map size.
  66099. *
  66100. * It does not account for the light projection as it was having too much
  66101. * instability during the light setup or during light position changes.
  66102. *
  66103. * Only valid if useContactHardeningShadow is true.
  66104. */
  66105. get: function () {
  66106. return this._contactHardeningLightSizeUVRatio;
  66107. },
  66108. /**
  66109. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66110. * Using a ratio helps keeping shape stability independently of the map size.
  66111. *
  66112. * It does not account for the light projection as it was having too much
  66113. * instability during the light setup or during light position changes.
  66114. *
  66115. * Only valid if useContactHardeningShadow is true.
  66116. */
  66117. set: function (contactHardeningLightSizeUVRatio) {
  66118. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66119. },
  66120. enumerable: true,
  66121. configurable: true
  66122. });
  66123. /**
  66124. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66125. * 0 means strongest and 1 would means no shadow.
  66126. * @returns the darkness.
  66127. */
  66128. ShadowGenerator.prototype.getDarkness = function () {
  66129. return this._darkness;
  66130. };
  66131. /**
  66132. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66133. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66134. * @returns the shadow generator allowing fluent coding.
  66135. */
  66136. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66137. if (darkness >= 1.0)
  66138. this._darkness = 1.0;
  66139. else if (darkness <= 0.0)
  66140. this._darkness = 0.0;
  66141. else
  66142. this._darkness = darkness;
  66143. return this;
  66144. };
  66145. /**
  66146. * Sets the ability to have transparent shadow (boolean).
  66147. * @param transparent True if transparent else False
  66148. * @returns the shadow generator allowing fluent coding
  66149. */
  66150. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66151. this._transparencyShadow = transparent;
  66152. return this;
  66153. };
  66154. /**
  66155. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66156. * @returns The render target texture if present otherwise, null
  66157. */
  66158. ShadowGenerator.prototype.getShadowMap = function () {
  66159. return this._shadowMap;
  66160. };
  66161. /**
  66162. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66163. * @returns The render target texture if the shadow map is present otherwise, null
  66164. */
  66165. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66166. if (this._shadowMap2) {
  66167. return this._shadowMap2;
  66168. }
  66169. return this._shadowMap;
  66170. };
  66171. /**
  66172. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66173. * @param mesh Mesh to add
  66174. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66175. * @returns the Shadow Generator itself
  66176. */
  66177. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66178. if (includeDescendants === void 0) { includeDescendants = true; }
  66179. if (!this._shadowMap) {
  66180. return this;
  66181. }
  66182. if (!this._shadowMap.renderList) {
  66183. this._shadowMap.renderList = [];
  66184. }
  66185. this._shadowMap.renderList.push(mesh);
  66186. if (includeDescendants) {
  66187. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66188. }
  66189. return this;
  66190. var _a;
  66191. };
  66192. /**
  66193. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66194. * @param mesh Mesh to remove
  66195. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66196. * @returns the Shadow Generator itself
  66197. */
  66198. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66199. if (includeDescendants === void 0) { includeDescendants = true; }
  66200. if (!this._shadowMap || !this._shadowMap.renderList) {
  66201. return this;
  66202. }
  66203. var index = this._shadowMap.renderList.indexOf(mesh);
  66204. if (index !== -1) {
  66205. this._shadowMap.renderList.splice(index, 1);
  66206. }
  66207. if (includeDescendants) {
  66208. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66209. var child = _a[_i];
  66210. this.removeShadowCaster(child);
  66211. }
  66212. }
  66213. return this;
  66214. };
  66215. /**
  66216. * Returns the associated light object.
  66217. * @returns the light generating the shadow
  66218. */
  66219. ShadowGenerator.prototype.getLight = function () {
  66220. return this._light;
  66221. };
  66222. ShadowGenerator.prototype._initializeGenerator = function () {
  66223. this._light._markMeshesAsLightDirty();
  66224. this._initializeShadowMap();
  66225. };
  66226. ShadowGenerator.prototype._initializeShadowMap = function () {
  66227. var _this = this;
  66228. // Render target
  66229. var engine = this._scene.getEngine();
  66230. if (engine.webGLVersion > 1) {
  66231. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66232. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66233. }
  66234. else {
  66235. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66236. }
  66237. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66238. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66239. this._shadowMap.anisotropicFilteringLevel = 1;
  66240. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66241. this._shadowMap.renderParticles = false;
  66242. this._shadowMap.ignoreCameraViewport = true;
  66243. // Record Face Index before render.
  66244. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66245. _this._currentFaceIndex = faceIndex;
  66246. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66247. engine.setColorWrite(false);
  66248. }
  66249. });
  66250. // Custom render function.
  66251. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66252. // Blur if required afer render.
  66253. this._shadowMap.onAfterUnbindObservable.add(function () {
  66254. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66255. engine.setColorWrite(true);
  66256. }
  66257. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66258. return;
  66259. }
  66260. var shadowMap = _this.getShadowMapForRendering();
  66261. if (shadowMap) {
  66262. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66263. }
  66264. });
  66265. // Clear according to the chosen filter.
  66266. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66267. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66268. this._shadowMap.onClearObservable.add(function (engine) {
  66269. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66270. engine.clear(clearOne, false, true, false);
  66271. }
  66272. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66273. engine.clear(clearZero, true, true, false);
  66274. }
  66275. else {
  66276. engine.clear(clearOne, true, true, false);
  66277. }
  66278. });
  66279. };
  66280. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66281. var _this = this;
  66282. var engine = this._scene.getEngine();
  66283. var targetSize = this._mapSize / this.blurScale;
  66284. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66285. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66286. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66287. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66288. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66289. }
  66290. if (this.useKernelBlur) {
  66291. 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);
  66292. this._kernelBlurXPostprocess.width = targetSize;
  66293. this._kernelBlurXPostprocess.height = targetSize;
  66294. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66295. effect.setTexture("textureSampler", _this._shadowMap);
  66296. });
  66297. 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);
  66298. this._kernelBlurXPostprocess.autoClear = false;
  66299. this._kernelBlurYPostprocess.autoClear = false;
  66300. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66301. this._kernelBlurXPostprocess.packedFloat = true;
  66302. this._kernelBlurYPostprocess.packedFloat = true;
  66303. }
  66304. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66305. }
  66306. else {
  66307. 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);
  66308. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66309. effect.setFloat2("screenSize", targetSize, targetSize);
  66310. effect.setTexture("textureSampler", _this._shadowMap);
  66311. });
  66312. this._boxBlurPostprocess.autoClear = false;
  66313. this._blurPostProcesses = [this._boxBlurPostprocess];
  66314. }
  66315. };
  66316. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66317. var index;
  66318. var engine = this._scene.getEngine();
  66319. if (depthOnlySubMeshes.length) {
  66320. engine.setColorWrite(false);
  66321. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66322. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66323. }
  66324. engine.setColorWrite(true);
  66325. }
  66326. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66327. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66328. }
  66329. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66330. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66331. }
  66332. if (this._transparencyShadow) {
  66333. for (index = 0; index < transparentSubMeshes.length; index++) {
  66334. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66335. }
  66336. }
  66337. };
  66338. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66339. var _this = this;
  66340. var mesh = subMesh.getRenderingMesh();
  66341. var scene = this._scene;
  66342. var engine = scene.getEngine();
  66343. var material = subMesh.getMaterial();
  66344. if (!material) {
  66345. return;
  66346. }
  66347. // Culling
  66348. engine.setState(material.backFaceCulling);
  66349. // Managing instances
  66350. var batch = mesh._getInstancesRenderList(subMesh._id);
  66351. if (batch.mustReturn) {
  66352. return;
  66353. }
  66354. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66355. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66356. engine.enableEffect(this._effect);
  66357. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66358. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66359. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66360. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66361. this._effect.setVector3("lightData", this._cachedDirection);
  66362. }
  66363. else {
  66364. this._effect.setVector3("lightData", this._cachedPosition);
  66365. }
  66366. if (scene.activeCamera) {
  66367. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66368. }
  66369. // Alpha test
  66370. if (material && material.needAlphaTesting()) {
  66371. var alphaTexture = material.getAlphaTestTexture();
  66372. if (alphaTexture) {
  66373. this._effect.setTexture("diffuseSampler", alphaTexture);
  66374. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66375. }
  66376. }
  66377. // Bones
  66378. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66379. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66380. }
  66381. // Morph targets
  66382. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66383. if (this.forceBackFacesOnly) {
  66384. engine.setState(true, 0, false, true);
  66385. }
  66386. // Draw
  66387. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66388. if (this.forceBackFacesOnly) {
  66389. engine.setState(true, 0, false, false);
  66390. }
  66391. }
  66392. else {
  66393. // Need to reset refresh rate of the shadowMap
  66394. if (this._shadowMap) {
  66395. this._shadowMap.resetRefreshCounter();
  66396. }
  66397. }
  66398. };
  66399. ShadowGenerator.prototype._applyFilterValues = function () {
  66400. if (!this._shadowMap) {
  66401. return;
  66402. }
  66403. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66404. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66405. }
  66406. else {
  66407. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66408. }
  66409. };
  66410. /**
  66411. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66412. * @param onCompiled Callback triggered at the and of the effects compilation
  66413. * @param options Sets of optional options forcing the compilation with different modes
  66414. */
  66415. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66416. var _this = this;
  66417. var localOptions = __assign({ useInstances: false }, options);
  66418. var shadowMap = this.getShadowMap();
  66419. if (!shadowMap) {
  66420. if (onCompiled) {
  66421. onCompiled(this);
  66422. }
  66423. return;
  66424. }
  66425. var renderList = shadowMap.renderList;
  66426. if (!renderList) {
  66427. if (onCompiled) {
  66428. onCompiled(this);
  66429. }
  66430. return;
  66431. }
  66432. var subMeshes = new Array();
  66433. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66434. var mesh = renderList_1[_i];
  66435. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66436. }
  66437. if (subMeshes.length === 0) {
  66438. if (onCompiled) {
  66439. onCompiled(this);
  66440. }
  66441. return;
  66442. }
  66443. var currentIndex = 0;
  66444. var checkReady = function () {
  66445. if (!_this._scene || !_this._scene.getEngine()) {
  66446. return;
  66447. }
  66448. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66449. currentIndex++;
  66450. if (currentIndex >= subMeshes.length) {
  66451. if (onCompiled) {
  66452. onCompiled(_this);
  66453. }
  66454. return;
  66455. }
  66456. }
  66457. setTimeout(checkReady, 16);
  66458. };
  66459. checkReady();
  66460. };
  66461. /**
  66462. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66463. * @param options Sets of optional options forcing the compilation with different modes
  66464. * @returns A promise that resolves when the compilation completes
  66465. */
  66466. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66467. var _this = this;
  66468. return new Promise(function (resolve) {
  66469. _this.forceCompilation(function () {
  66470. resolve();
  66471. }, options);
  66472. });
  66473. };
  66474. /**
  66475. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66476. * @param subMesh The submesh we want to render in the shadow map
  66477. * @param useInstances Defines wether will draw in the map using instances
  66478. * @returns true if ready otherwise, false
  66479. */
  66480. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66481. var defines = [];
  66482. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66483. defines.push("#define FLOAT");
  66484. }
  66485. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66486. defines.push("#define ESM");
  66487. }
  66488. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66489. defines.push("#define DEPTHTEXTURE");
  66490. }
  66491. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66492. var mesh = subMesh.getMesh();
  66493. var material = subMesh.getMaterial();
  66494. // Normal bias.
  66495. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66496. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66497. defines.push("#define NORMAL");
  66498. if (mesh.nonUniformScaling) {
  66499. defines.push("#define NONUNIFORMSCALING");
  66500. }
  66501. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66502. defines.push("#define DIRECTIONINLIGHTDATA");
  66503. }
  66504. }
  66505. // Alpha test
  66506. if (material && material.needAlphaTesting()) {
  66507. var alphaTexture = material.getAlphaTestTexture();
  66508. if (alphaTexture) {
  66509. defines.push("#define ALPHATEST");
  66510. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66511. attribs.push(BABYLON.VertexBuffer.UVKind);
  66512. defines.push("#define UV1");
  66513. }
  66514. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66515. if (alphaTexture.coordinatesIndex === 1) {
  66516. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66517. defines.push("#define UV2");
  66518. }
  66519. }
  66520. }
  66521. }
  66522. // Bones
  66523. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66524. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66525. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66526. if (mesh.numBoneInfluencers > 4) {
  66527. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66528. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66529. }
  66530. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66531. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66532. }
  66533. else {
  66534. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66535. }
  66536. // Morph targets
  66537. var manager = mesh.morphTargetManager;
  66538. var morphInfluencers = 0;
  66539. if (manager) {
  66540. if (manager.numInfluencers > 0) {
  66541. defines.push("#define MORPHTARGETS");
  66542. morphInfluencers = manager.numInfluencers;
  66543. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66544. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66545. }
  66546. }
  66547. // Instances
  66548. if (useInstances) {
  66549. defines.push("#define INSTANCES");
  66550. attribs.push("world0");
  66551. attribs.push("world1");
  66552. attribs.push("world2");
  66553. attribs.push("world3");
  66554. }
  66555. // Get correct effect
  66556. var join = defines.join("\n");
  66557. if (this._cachedDefines !== join) {
  66558. this._cachedDefines = join;
  66559. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66560. }
  66561. if (!this._effect.isReady()) {
  66562. return false;
  66563. }
  66564. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66565. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66566. this._initializeBlurRTTAndPostProcesses();
  66567. }
  66568. }
  66569. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66570. return false;
  66571. }
  66572. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66573. return false;
  66574. }
  66575. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66576. return false;
  66577. }
  66578. return true;
  66579. };
  66580. /**
  66581. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66582. * @param defines Defines of the material we want to update
  66583. * @param lightIndex Index of the light in the enabled light list of the material
  66584. */
  66585. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66586. var scene = this._scene;
  66587. var light = this._light;
  66588. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66589. return;
  66590. }
  66591. defines["SHADOW" + lightIndex] = true;
  66592. if (this.useContactHardeningShadow) {
  66593. defines["SHADOWPCSS" + lightIndex] = true;
  66594. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66595. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66596. }
  66597. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66598. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66599. }
  66600. // else default to high.
  66601. }
  66602. if (this.usePercentageCloserFiltering) {
  66603. defines["SHADOWPCF" + lightIndex] = true;
  66604. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66605. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66606. }
  66607. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66608. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66609. }
  66610. // else default to high.
  66611. }
  66612. else if (this.usePoissonSampling) {
  66613. defines["SHADOWPOISSON" + lightIndex] = true;
  66614. }
  66615. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66616. defines["SHADOWESM" + lightIndex] = true;
  66617. }
  66618. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66619. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66620. }
  66621. if (light.needCube()) {
  66622. defines["SHADOWCUBE" + lightIndex] = true;
  66623. }
  66624. };
  66625. /**
  66626. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66627. * defined in the generator but impacting the effect).
  66628. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66629. * @param effect The effect we are binfing the information for
  66630. */
  66631. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66632. var light = this._light;
  66633. var scene = this._scene;
  66634. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66635. return;
  66636. }
  66637. var camera = scene.activeCamera;
  66638. if (!camera) {
  66639. return;
  66640. }
  66641. var shadowMap = this.getShadowMap();
  66642. if (!shadowMap) {
  66643. return;
  66644. }
  66645. if (!light.needCube()) {
  66646. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66647. }
  66648. // Only PCF uses depth stencil texture.
  66649. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66650. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66651. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66652. }
  66653. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66654. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66655. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66656. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66657. }
  66658. else {
  66659. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66660. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66661. }
  66662. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66663. };
  66664. /**
  66665. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66666. * (eq to shadow prjection matrix * light transform matrix)
  66667. * @returns The transform matrix used to create the shadow map
  66668. */
  66669. ShadowGenerator.prototype.getTransformMatrix = function () {
  66670. var scene = this._scene;
  66671. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66672. return this._transformMatrix;
  66673. }
  66674. this._currentRenderID = scene.getRenderId();
  66675. this._currentFaceIndexCache = this._currentFaceIndex;
  66676. var lightPosition = this._light.position;
  66677. if (this._light.computeTransformedInformation()) {
  66678. lightPosition = this._light.transformedPosition;
  66679. }
  66680. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66681. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66682. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66683. }
  66684. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66685. this._cachedPosition.copyFrom(lightPosition);
  66686. this._cachedDirection.copyFrom(this._lightDirection);
  66687. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66688. var shadowMap = this.getShadowMap();
  66689. if (shadowMap) {
  66690. var renderList = shadowMap.renderList;
  66691. if (renderList) {
  66692. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66693. }
  66694. }
  66695. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66696. }
  66697. return this._transformMatrix;
  66698. };
  66699. /**
  66700. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66701. * Cube and 2D textures for instance.
  66702. */
  66703. ShadowGenerator.prototype.recreateShadowMap = function () {
  66704. var shadowMap = this._shadowMap;
  66705. if (!shadowMap) {
  66706. return;
  66707. }
  66708. // Track render list.
  66709. var renderList = shadowMap.renderList;
  66710. // Clean up existing data.
  66711. this._disposeRTTandPostProcesses();
  66712. // Reinitializes.
  66713. this._initializeGenerator();
  66714. // Reaffect the filter to ensure a correct fallback if necessary.
  66715. this.filter = this.filter;
  66716. // Reaffect the filter.
  66717. this._applyFilterValues();
  66718. // Reaffect Render List.
  66719. this._shadowMap.renderList = renderList;
  66720. };
  66721. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66722. if (this._shadowMap2) {
  66723. this._shadowMap2.dispose();
  66724. this._shadowMap2 = null;
  66725. }
  66726. if (this._boxBlurPostprocess) {
  66727. this._boxBlurPostprocess.dispose();
  66728. this._boxBlurPostprocess = null;
  66729. }
  66730. if (this._kernelBlurXPostprocess) {
  66731. this._kernelBlurXPostprocess.dispose();
  66732. this._kernelBlurXPostprocess = null;
  66733. }
  66734. if (this._kernelBlurYPostprocess) {
  66735. this._kernelBlurYPostprocess.dispose();
  66736. this._kernelBlurYPostprocess = null;
  66737. }
  66738. this._blurPostProcesses = [];
  66739. };
  66740. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66741. if (this._shadowMap) {
  66742. this._shadowMap.dispose();
  66743. this._shadowMap = null;
  66744. }
  66745. this._disposeBlurPostProcesses();
  66746. };
  66747. /**
  66748. * Disposes the ShadowGenerator.
  66749. * Returns nothing.
  66750. */
  66751. ShadowGenerator.prototype.dispose = function () {
  66752. this._disposeRTTandPostProcesses();
  66753. if (this._light) {
  66754. this._light._shadowGenerator = null;
  66755. this._light._markMeshesAsLightDirty();
  66756. }
  66757. };
  66758. /**
  66759. * Serializes the shadow generator setup to a json object.
  66760. * @returns The serialized JSON object
  66761. */
  66762. ShadowGenerator.prototype.serialize = function () {
  66763. var serializationObject = {};
  66764. var shadowMap = this.getShadowMap();
  66765. if (!shadowMap) {
  66766. return serializationObject;
  66767. }
  66768. serializationObject.lightId = this._light.id;
  66769. serializationObject.mapSize = shadowMap.getRenderSize();
  66770. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66771. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66772. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66773. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66774. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66775. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66776. serializationObject.depthScale = this.depthScale;
  66777. serializationObject.darkness = this.getDarkness();
  66778. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66779. serializationObject.blurKernel = this.blurKernel;
  66780. serializationObject.blurScale = this.blurScale;
  66781. serializationObject.useKernelBlur = this.useKernelBlur;
  66782. serializationObject.transparencyShadow = this._transparencyShadow;
  66783. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66784. serializationObject.bias = this.bias;
  66785. serializationObject.normalBias = this.normalBias;
  66786. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66787. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66788. serializationObject.filteringQuality = this.filteringQuality;
  66789. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66790. serializationObject.renderList = [];
  66791. if (shadowMap.renderList) {
  66792. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66793. var mesh = shadowMap.renderList[meshIndex];
  66794. serializationObject.renderList.push(mesh.id);
  66795. }
  66796. }
  66797. return serializationObject;
  66798. };
  66799. /**
  66800. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66801. * @param parsedShadowGenerator The JSON object to parse
  66802. * @param scene The scene to create the shadow map for
  66803. * @returns The parsed shadow generator
  66804. */
  66805. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66806. //casting to point light, as light is missing the position attr and typescript complains.
  66807. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66808. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66809. var shadowMap = shadowGenerator.getShadowMap();
  66810. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66811. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66812. meshes.forEach(function (mesh) {
  66813. if (!shadowMap) {
  66814. return;
  66815. }
  66816. if (!shadowMap.renderList) {
  66817. shadowMap.renderList = [];
  66818. }
  66819. shadowMap.renderList.push(mesh);
  66820. });
  66821. }
  66822. if (parsedShadowGenerator.usePoissonSampling) {
  66823. shadowGenerator.usePoissonSampling = true;
  66824. }
  66825. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66826. shadowGenerator.useExponentialShadowMap = true;
  66827. }
  66828. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66829. shadowGenerator.useBlurExponentialShadowMap = true;
  66830. }
  66831. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66832. shadowGenerator.useCloseExponentialShadowMap = true;
  66833. }
  66834. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66835. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66836. }
  66837. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66838. shadowGenerator.usePercentageCloserFiltering = true;
  66839. }
  66840. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66841. shadowGenerator.useContactHardeningShadow = true;
  66842. }
  66843. if (parsedShadowGenerator.filteringQuality) {
  66844. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66845. }
  66846. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66847. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66848. }
  66849. // Backward compat
  66850. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66851. shadowGenerator.useExponentialShadowMap = true;
  66852. }
  66853. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66854. shadowGenerator.useBlurExponentialShadowMap = true;
  66855. }
  66856. if (parsedShadowGenerator.depthScale) {
  66857. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66858. }
  66859. if (parsedShadowGenerator.blurScale) {
  66860. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66861. }
  66862. if (parsedShadowGenerator.blurBoxOffset) {
  66863. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66864. }
  66865. if (parsedShadowGenerator.useKernelBlur) {
  66866. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66867. }
  66868. if (parsedShadowGenerator.blurKernel) {
  66869. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66870. }
  66871. if (parsedShadowGenerator.bias !== undefined) {
  66872. shadowGenerator.bias = parsedShadowGenerator.bias;
  66873. }
  66874. if (parsedShadowGenerator.normalBias !== undefined) {
  66875. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66876. }
  66877. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66878. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66879. }
  66880. if (parsedShadowGenerator.darkness) {
  66881. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66882. }
  66883. if (parsedShadowGenerator.transparencyShadow) {
  66884. shadowGenerator.setTransparencyShadow(true);
  66885. }
  66886. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66887. return shadowGenerator;
  66888. };
  66889. /**
  66890. * Shadow generator mode None: no filtering applied.
  66891. */
  66892. ShadowGenerator.FILTER_NONE = 0;
  66893. /**
  66894. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66895. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66896. */
  66897. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66898. /**
  66899. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66900. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66901. */
  66902. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66903. /**
  66904. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66905. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66906. */
  66907. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66908. /**
  66909. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66910. * edge artifacts on steep falloff.
  66911. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66912. */
  66913. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66914. /**
  66915. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66916. * edge artifacts on steep falloff.
  66917. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66918. */
  66919. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66920. /**
  66921. * Shadow generator mode PCF: Percentage Closer Filtering
  66922. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66923. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66924. */
  66925. ShadowGenerator.FILTER_PCF = 6;
  66926. /**
  66927. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66928. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66929. * Contact Hardening
  66930. */
  66931. ShadowGenerator.FILTER_PCSS = 7;
  66932. /**
  66933. * Reserved for PCF and PCSS
  66934. * Highest Quality.
  66935. *
  66936. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66937. *
  66938. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66939. */
  66940. ShadowGenerator.QUALITY_HIGH = 0;
  66941. /**
  66942. * Reserved for PCF and PCSS
  66943. * Good tradeoff for quality/perf cross devices
  66944. *
  66945. * Execute PCF on a 3*3 kernel.
  66946. *
  66947. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66948. */
  66949. ShadowGenerator.QUALITY_MEDIUM = 1;
  66950. /**
  66951. * Reserved for PCF and PCSS
  66952. * The lowest quality but the fastest.
  66953. *
  66954. * Execute PCF on a 1*1 kernel.
  66955. *
  66956. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66957. */
  66958. ShadowGenerator.QUALITY_LOW = 2;
  66959. return ShadowGenerator;
  66960. }());
  66961. BABYLON.ShadowGenerator = ShadowGenerator;
  66962. })(BABYLON || (BABYLON = {}));
  66963. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66964. var BABYLON;
  66965. (function (BABYLON) {
  66966. var DefaultLoadingScreen = /** @class */ (function () {
  66967. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66968. if (_loadingText === void 0) { _loadingText = ""; }
  66969. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66970. var _this = this;
  66971. this._renderingCanvas = _renderingCanvas;
  66972. this._loadingText = _loadingText;
  66973. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66974. // Resize
  66975. this._resizeLoadingUI = function () {
  66976. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66977. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66978. if (!_this._loadingDiv) {
  66979. return;
  66980. }
  66981. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66982. _this._loadingDiv.style.left = canvasRect.left + "px";
  66983. _this._loadingDiv.style.top = canvasRect.top + "px";
  66984. _this._loadingDiv.style.width = canvasRect.width + "px";
  66985. _this._loadingDiv.style.height = canvasRect.height + "px";
  66986. };
  66987. }
  66988. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66989. if (this._loadingDiv) {
  66990. // Do not add a loading screen if there is already one
  66991. return;
  66992. }
  66993. this._loadingDiv = document.createElement("div");
  66994. this._loadingDiv.id = "babylonjsLoadingDiv";
  66995. this._loadingDiv.style.opacity = "0";
  66996. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66997. this._loadingDiv.style.pointerEvents = "none";
  66998. // Loading text
  66999. this._loadingTextDiv = document.createElement("div");
  67000. this._loadingTextDiv.style.position = "absolute";
  67001. this._loadingTextDiv.style.left = "0";
  67002. this._loadingTextDiv.style.top = "50%";
  67003. this._loadingTextDiv.style.marginTop = "80px";
  67004. this._loadingTextDiv.style.width = "100%";
  67005. this._loadingTextDiv.style.height = "20px";
  67006. this._loadingTextDiv.style.fontFamily = "Arial";
  67007. this._loadingTextDiv.style.fontSize = "14px";
  67008. this._loadingTextDiv.style.color = "white";
  67009. this._loadingTextDiv.style.textAlign = "center";
  67010. this._loadingTextDiv.innerHTML = "Loading";
  67011. this._loadingDiv.appendChild(this._loadingTextDiv);
  67012. //set the predefined text
  67013. this._loadingTextDiv.innerHTML = this._loadingText;
  67014. // Generating keyframes
  67015. var style = document.createElement('style');
  67016. style.type = 'text/css';
  67017. 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 }";
  67018. style.innerHTML = keyFrames;
  67019. document.getElementsByTagName('head')[0].appendChild(style);
  67020. // Loading img
  67021. var imgBack = new Image();
  67022. 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";
  67023. imgBack.style.position = "absolute";
  67024. imgBack.style.left = "50%";
  67025. imgBack.style.top = "50%";
  67026. imgBack.style.marginLeft = "-60px";
  67027. imgBack.style.marginTop = "-60px";
  67028. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67029. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67030. imgBack.style.transformOrigin = "50% 50%";
  67031. imgBack.style.webkitTransformOrigin = "50% 50%";
  67032. this._loadingDiv.appendChild(imgBack);
  67033. this._resizeLoadingUI();
  67034. window.addEventListener("resize", this._resizeLoadingUI);
  67035. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67036. document.body.appendChild(this._loadingDiv);
  67037. this._loadingDiv.style.opacity = "1";
  67038. };
  67039. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67040. var _this = this;
  67041. if (!this._loadingDiv) {
  67042. return;
  67043. }
  67044. var onTransitionEnd = function () {
  67045. if (!_this._loadingDiv) {
  67046. return;
  67047. }
  67048. document.body.removeChild(_this._loadingDiv);
  67049. window.removeEventListener("resize", _this._resizeLoadingUI);
  67050. _this._loadingDiv = null;
  67051. };
  67052. this._loadingDiv.style.opacity = "0";
  67053. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67054. };
  67055. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67056. set: function (text) {
  67057. this._loadingText = text;
  67058. if (this._loadingTextDiv) {
  67059. this._loadingTextDiv.innerHTML = this._loadingText;
  67060. }
  67061. },
  67062. enumerable: true,
  67063. configurable: true
  67064. });
  67065. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67066. get: function () {
  67067. return this._loadingDivBackgroundColor;
  67068. },
  67069. set: function (color) {
  67070. this._loadingDivBackgroundColor = color;
  67071. if (!this._loadingDiv) {
  67072. return;
  67073. }
  67074. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67075. },
  67076. enumerable: true,
  67077. configurable: true
  67078. });
  67079. return DefaultLoadingScreen;
  67080. }());
  67081. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67082. })(BABYLON || (BABYLON = {}));
  67083. //# sourceMappingURL=babylon.loadingScreen.js.map
  67084. var BABYLON;
  67085. (function (BABYLON) {
  67086. var SceneLoaderProgressEvent = /** @class */ (function () {
  67087. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67088. this.lengthComputable = lengthComputable;
  67089. this.loaded = loaded;
  67090. this.total = total;
  67091. }
  67092. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67093. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67094. };
  67095. return SceneLoaderProgressEvent;
  67096. }());
  67097. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67098. var SceneLoader = /** @class */ (function () {
  67099. function SceneLoader() {
  67100. }
  67101. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67102. get: function () {
  67103. return 0;
  67104. },
  67105. enumerable: true,
  67106. configurable: true
  67107. });
  67108. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67109. get: function () {
  67110. return 1;
  67111. },
  67112. enumerable: true,
  67113. configurable: true
  67114. });
  67115. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67116. get: function () {
  67117. return 2;
  67118. },
  67119. enumerable: true,
  67120. configurable: true
  67121. });
  67122. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67123. get: function () {
  67124. return 3;
  67125. },
  67126. enumerable: true,
  67127. configurable: true
  67128. });
  67129. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67130. get: function () {
  67131. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67132. },
  67133. set: function (value) {
  67134. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67135. },
  67136. enumerable: true,
  67137. configurable: true
  67138. });
  67139. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67140. get: function () {
  67141. return SceneLoader._ShowLoadingScreen;
  67142. },
  67143. set: function (value) {
  67144. SceneLoader._ShowLoadingScreen = value;
  67145. },
  67146. enumerable: true,
  67147. configurable: true
  67148. });
  67149. Object.defineProperty(SceneLoader, "loggingLevel", {
  67150. get: function () {
  67151. return SceneLoader._loggingLevel;
  67152. },
  67153. set: function (value) {
  67154. SceneLoader._loggingLevel = value;
  67155. },
  67156. enumerable: true,
  67157. configurable: true
  67158. });
  67159. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67160. get: function () {
  67161. return SceneLoader._CleanBoneMatrixWeights;
  67162. },
  67163. set: function (value) {
  67164. SceneLoader._CleanBoneMatrixWeights = value;
  67165. },
  67166. enumerable: true,
  67167. configurable: true
  67168. });
  67169. SceneLoader._getDefaultPlugin = function () {
  67170. return SceneLoader._registeredPlugins[".babylon"];
  67171. };
  67172. SceneLoader._getPluginForExtension = function (extension) {
  67173. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67174. if (registeredPlugin) {
  67175. return registeredPlugin;
  67176. }
  67177. 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");
  67178. return SceneLoader._getDefaultPlugin();
  67179. };
  67180. SceneLoader._getPluginForDirectLoad = function (data) {
  67181. for (var extension in SceneLoader._registeredPlugins) {
  67182. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67183. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67184. return SceneLoader._registeredPlugins[extension];
  67185. }
  67186. }
  67187. return SceneLoader._getDefaultPlugin();
  67188. };
  67189. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67190. if (sceneFilename.name) {
  67191. sceneFilename = sceneFilename.name;
  67192. }
  67193. var queryStringPosition = sceneFilename.indexOf("?");
  67194. if (queryStringPosition !== -1) {
  67195. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67196. }
  67197. var dotPosition = sceneFilename.lastIndexOf(".");
  67198. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67199. return SceneLoader._getPluginForExtension(extension);
  67200. };
  67201. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67202. SceneLoader._getDirectLoad = function (sceneFilename) {
  67203. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67204. return sceneFilename.substr(5);
  67205. }
  67206. return null;
  67207. };
  67208. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67209. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67210. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67211. var plugin;
  67212. if (registeredPlugin.plugin.createPlugin) {
  67213. plugin = registeredPlugin.plugin.createPlugin();
  67214. }
  67215. else {
  67216. plugin = registeredPlugin.plugin;
  67217. }
  67218. var useArrayBuffer = registeredPlugin.isBinary;
  67219. var database;
  67220. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67221. var dataCallback = function (data, responseURL) {
  67222. if (scene.isDisposed) {
  67223. onError("Scene has been disposed");
  67224. return;
  67225. }
  67226. scene.database = database;
  67227. onSuccess(plugin, data, responseURL);
  67228. };
  67229. var request = null;
  67230. var pluginDisposed = false;
  67231. var onDisposeObservable = plugin.onDisposeObservable;
  67232. if (onDisposeObservable) {
  67233. onDisposeObservable.add(function () {
  67234. pluginDisposed = true;
  67235. if (request) {
  67236. request.abort();
  67237. request = null;
  67238. }
  67239. onDispose();
  67240. });
  67241. }
  67242. var manifestChecked = function () {
  67243. if (pluginDisposed) {
  67244. return;
  67245. }
  67246. var url = rootUrl + sceneFilename;
  67247. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67248. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67249. } : undefined, database, useArrayBuffer, function (request, exception) {
  67250. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67251. });
  67252. };
  67253. if (directLoad) {
  67254. dataCallback(directLoad);
  67255. return plugin;
  67256. }
  67257. if (rootUrl.indexOf("file:") === -1) {
  67258. var engine = scene.getEngine();
  67259. var canUseOfflineSupport = engine.enableOfflineSupport;
  67260. if (canUseOfflineSupport) {
  67261. // Also check for exceptions
  67262. var exceptionFound = false;
  67263. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67264. var regex = _a[_i];
  67265. if (regex.test(rootUrl + sceneFilename)) {
  67266. exceptionFound = true;
  67267. break;
  67268. }
  67269. }
  67270. canUseOfflineSupport = !exceptionFound;
  67271. }
  67272. if (canUseOfflineSupport) {
  67273. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67274. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67275. }
  67276. else {
  67277. manifestChecked();
  67278. }
  67279. }
  67280. // Loading file from disk via input file or drag'n'drop
  67281. else {
  67282. var fileOrString = sceneFilename;
  67283. if (fileOrString.name) { // File
  67284. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67285. }
  67286. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67287. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67288. }
  67289. else {
  67290. onError("Unable to find file named " + sceneFilename);
  67291. }
  67292. }
  67293. return plugin;
  67294. };
  67295. // Public functions
  67296. SceneLoader.GetPluginForExtension = function (extension) {
  67297. return SceneLoader._getPluginForExtension(extension).plugin;
  67298. };
  67299. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67300. return !!SceneLoader._registeredPlugins[extension];
  67301. };
  67302. SceneLoader.RegisterPlugin = function (plugin) {
  67303. if (typeof plugin.extensions === "string") {
  67304. var extension = plugin.extensions;
  67305. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67306. plugin: plugin,
  67307. isBinary: false
  67308. };
  67309. }
  67310. else {
  67311. var extensions = plugin.extensions;
  67312. Object.keys(extensions).forEach(function (extension) {
  67313. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67314. plugin: plugin,
  67315. isBinary: extensions[extension].isBinary
  67316. };
  67317. });
  67318. }
  67319. };
  67320. /**
  67321. * Import meshes into a scene
  67322. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67323. * @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)
  67324. * @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)
  67325. * @param scene the instance of BABYLON.Scene to append to
  67326. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67327. * @param onProgress a callback with a progress event for each file being loaded
  67328. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67329. * @param pluginExtension the extension used to determine the plugin
  67330. * @returns The loaded plugin
  67331. */
  67332. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67333. if (sceneFilename === void 0) { sceneFilename = ""; }
  67334. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67335. if (onSuccess === void 0) { onSuccess = null; }
  67336. if (onProgress === void 0) { onProgress = null; }
  67337. if (onError === void 0) { onError = null; }
  67338. if (pluginExtension === void 0) { pluginExtension = null; }
  67339. if (!scene) {
  67340. BABYLON.Tools.Error("No scene available to import mesh to");
  67341. return null;
  67342. }
  67343. if (!sceneFilename) {
  67344. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67345. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67346. }
  67347. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67348. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67349. return null;
  67350. }
  67351. var loadingToken = {};
  67352. scene._addPendingData(loadingToken);
  67353. var disposeHandler = function () {
  67354. scene._removePendingData(loadingToken);
  67355. };
  67356. var errorHandler = function (message, exception) {
  67357. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67358. if (onError) {
  67359. onError(scene, errorMessage, exception);
  67360. }
  67361. else {
  67362. BABYLON.Tools.Error(errorMessage);
  67363. // should the exception be thrown?
  67364. }
  67365. disposeHandler();
  67366. };
  67367. var progressHandler = onProgress ? function (event) {
  67368. try {
  67369. onProgress(event);
  67370. }
  67371. catch (e) {
  67372. errorHandler("Error in onProgress callback", e);
  67373. }
  67374. } : undefined;
  67375. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67376. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67377. if (onSuccess) {
  67378. try {
  67379. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67380. }
  67381. catch (e) {
  67382. errorHandler("Error in onSuccess callback", e);
  67383. }
  67384. }
  67385. scene._removePendingData(loadingToken);
  67386. };
  67387. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67388. if (plugin.rewriteRootURL) {
  67389. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67390. }
  67391. if (sceneFilename === "") {
  67392. if (sceneFilename === "") {
  67393. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67394. }
  67395. }
  67396. if (plugin.importMesh) {
  67397. var syncedPlugin = plugin;
  67398. var meshes = new Array();
  67399. var particleSystems = new Array();
  67400. var skeletons = new Array();
  67401. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67402. return;
  67403. }
  67404. scene.loadingPluginName = plugin.name;
  67405. successHandler(meshes, particleSystems, skeletons, []);
  67406. }
  67407. else {
  67408. var asyncedPlugin = plugin;
  67409. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67410. scene.loadingPluginName = plugin.name;
  67411. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67412. }).catch(function (error) {
  67413. errorHandler(error.message, error);
  67414. });
  67415. }
  67416. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67417. };
  67418. /**
  67419. * Import meshes into a scene
  67420. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67421. * @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)
  67422. * @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)
  67423. * @param scene the instance of BABYLON.Scene to append to
  67424. * @param onProgress a callback with a progress event for each file being loaded
  67425. * @param pluginExtension the extension used to determine the plugin
  67426. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67427. */
  67428. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67429. if (sceneFilename === void 0) { sceneFilename = ""; }
  67430. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67431. if (onProgress === void 0) { onProgress = null; }
  67432. if (pluginExtension === void 0) { pluginExtension = null; }
  67433. return new Promise(function (resolve, reject) {
  67434. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67435. resolve({
  67436. meshes: meshes,
  67437. particleSystems: particleSystems,
  67438. skeletons: skeletons,
  67439. animationGroups: animationGroups
  67440. });
  67441. }, onProgress, function (scene, message, exception) {
  67442. reject(exception || new Error(message));
  67443. }, pluginExtension);
  67444. });
  67445. };
  67446. /**
  67447. * Load a scene
  67448. * @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)
  67449. * @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)
  67450. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67451. * @param onSuccess a callback with the scene when import succeeds
  67452. * @param onProgress a callback with a progress event for each file being loaded
  67453. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67454. * @param pluginExtension the extension used to determine the plugin
  67455. * @returns The loaded plugin
  67456. */
  67457. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67458. if (onSuccess === void 0) { onSuccess = null; }
  67459. if (onProgress === void 0) { onProgress = null; }
  67460. if (onError === void 0) { onError = null; }
  67461. if (pluginExtension === void 0) { pluginExtension = null; }
  67462. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67463. };
  67464. /**
  67465. * Load a scene
  67466. * @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)
  67467. * @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)
  67468. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67469. * @param onProgress a callback with a progress event for each file being loaded
  67470. * @param pluginExtension the extension used to determine the plugin
  67471. * @returns The loaded scene
  67472. */
  67473. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67474. if (onProgress === void 0) { onProgress = null; }
  67475. if (pluginExtension === void 0) { pluginExtension = null; }
  67476. return new Promise(function (resolve, reject) {
  67477. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67478. resolve(scene);
  67479. }, onProgress, function (scene, message, exception) {
  67480. reject(exception || new Error(message));
  67481. }, pluginExtension);
  67482. });
  67483. };
  67484. /**
  67485. * Append a scene
  67486. * @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)
  67487. * @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)
  67488. * @param scene is the instance of BABYLON.Scene to append to
  67489. * @param onSuccess a callback with the scene when import succeeds
  67490. * @param onProgress a callback with a progress event for each file being loaded
  67491. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67492. * @param pluginExtension the extension used to determine the plugin
  67493. * @returns The loaded plugin
  67494. */
  67495. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67496. if (sceneFilename === void 0) { sceneFilename = ""; }
  67497. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67498. if (onSuccess === void 0) { onSuccess = null; }
  67499. if (onProgress === void 0) { onProgress = null; }
  67500. if (onError === void 0) { onError = null; }
  67501. if (pluginExtension === void 0) { pluginExtension = null; }
  67502. if (!scene) {
  67503. BABYLON.Tools.Error("No scene available to append to");
  67504. return null;
  67505. }
  67506. if (!sceneFilename) {
  67507. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67508. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67509. }
  67510. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67511. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67512. return null;
  67513. }
  67514. if (SceneLoader.ShowLoadingScreen) {
  67515. scene.getEngine().displayLoadingUI();
  67516. }
  67517. var loadingToken = {};
  67518. scene._addPendingData(loadingToken);
  67519. var disposeHandler = function () {
  67520. scene._removePendingData(loadingToken);
  67521. scene.getEngine().hideLoadingUI();
  67522. };
  67523. var errorHandler = function (message, exception) {
  67524. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67525. if (onError) {
  67526. onError(scene, errorMessage, exception);
  67527. }
  67528. else {
  67529. BABYLON.Tools.Error(errorMessage);
  67530. // should the exception be thrown?
  67531. }
  67532. disposeHandler();
  67533. };
  67534. var progressHandler = onProgress ? function (event) {
  67535. try {
  67536. onProgress(event);
  67537. }
  67538. catch (e) {
  67539. errorHandler("Error in onProgress callback", e);
  67540. }
  67541. } : undefined;
  67542. var successHandler = function () {
  67543. if (onSuccess) {
  67544. try {
  67545. onSuccess(scene);
  67546. }
  67547. catch (e) {
  67548. errorHandler("Error in onSuccess callback", e);
  67549. }
  67550. }
  67551. scene._removePendingData(loadingToken);
  67552. };
  67553. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67554. if (sceneFilename === "") {
  67555. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67556. }
  67557. if (plugin.load) {
  67558. var syncedPlugin = plugin;
  67559. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67560. return;
  67561. }
  67562. scene.loadingPluginName = plugin.name;
  67563. successHandler();
  67564. }
  67565. else {
  67566. var asyncedPlugin = plugin;
  67567. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67568. scene.loadingPluginName = plugin.name;
  67569. successHandler();
  67570. }).catch(function (error) {
  67571. errorHandler(error.message, error);
  67572. });
  67573. }
  67574. if (SceneLoader.ShowLoadingScreen) {
  67575. scene.executeWhenReady(function () {
  67576. scene.getEngine().hideLoadingUI();
  67577. });
  67578. }
  67579. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67580. };
  67581. /**
  67582. * Append a scene
  67583. * @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)
  67584. * @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)
  67585. * @param scene is the instance of BABYLON.Scene to append to
  67586. * @param onProgress a callback with a progress event for each file being loaded
  67587. * @param pluginExtension the extension used to determine the plugin
  67588. * @returns The given scene
  67589. */
  67590. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67591. if (sceneFilename === void 0) { sceneFilename = ""; }
  67592. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67593. if (onProgress === void 0) { onProgress = null; }
  67594. if (pluginExtension === void 0) { pluginExtension = null; }
  67595. return new Promise(function (resolve, reject) {
  67596. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67597. resolve(scene);
  67598. }, onProgress, function (scene, message, exception) {
  67599. reject(exception || new Error(message));
  67600. }, pluginExtension);
  67601. });
  67602. };
  67603. /**
  67604. * Load a scene into an asset container
  67605. * @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)
  67606. * @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)
  67607. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67608. * @param onSuccess a callback with the scene when import succeeds
  67609. * @param onProgress a callback with a progress event for each file being loaded
  67610. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67611. * @param pluginExtension the extension used to determine the plugin
  67612. * @returns The loaded plugin
  67613. */
  67614. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67615. if (sceneFilename === void 0) { sceneFilename = ""; }
  67616. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67617. if (onSuccess === void 0) { onSuccess = null; }
  67618. if (onProgress === void 0) { onProgress = null; }
  67619. if (onError === void 0) { onError = null; }
  67620. if (pluginExtension === void 0) { pluginExtension = null; }
  67621. if (!scene) {
  67622. BABYLON.Tools.Error("No scene available to load asset container to");
  67623. return null;
  67624. }
  67625. if (!sceneFilename) {
  67626. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67627. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67628. }
  67629. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67630. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67631. return null;
  67632. }
  67633. var loadingToken = {};
  67634. scene._addPendingData(loadingToken);
  67635. var disposeHandler = function () {
  67636. scene._removePendingData(loadingToken);
  67637. };
  67638. var errorHandler = function (message, exception) {
  67639. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67640. if (onError) {
  67641. onError(scene, errorMessage, exception);
  67642. }
  67643. else {
  67644. BABYLON.Tools.Error(errorMessage);
  67645. // should the exception be thrown?
  67646. }
  67647. disposeHandler();
  67648. };
  67649. var progressHandler = onProgress ? function (event) {
  67650. try {
  67651. onProgress(event);
  67652. }
  67653. catch (e) {
  67654. errorHandler("Error in onProgress callback", e);
  67655. }
  67656. } : undefined;
  67657. var successHandler = function (assets) {
  67658. if (onSuccess) {
  67659. try {
  67660. onSuccess(assets);
  67661. }
  67662. catch (e) {
  67663. errorHandler("Error in onSuccess callback", e);
  67664. }
  67665. }
  67666. scene._removePendingData(loadingToken);
  67667. };
  67668. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67669. if (plugin.loadAssetContainer) {
  67670. var syncedPlugin = plugin;
  67671. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67672. if (!assetContainer) {
  67673. return;
  67674. }
  67675. scene.loadingPluginName = plugin.name;
  67676. successHandler(assetContainer);
  67677. }
  67678. else if (plugin.loadAssetContainerAsync) {
  67679. var asyncedPlugin = plugin;
  67680. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67681. scene.loadingPluginName = plugin.name;
  67682. successHandler(assetContainer);
  67683. }).catch(function (error) {
  67684. errorHandler(error.message, error);
  67685. });
  67686. }
  67687. else {
  67688. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67689. }
  67690. if (SceneLoader.ShowLoadingScreen) {
  67691. scene.executeWhenReady(function () {
  67692. scene.getEngine().hideLoadingUI();
  67693. });
  67694. }
  67695. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67696. };
  67697. /**
  67698. * Load a scene into an asset container
  67699. * @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)
  67700. * @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)
  67701. * @param scene is the instance of BABYLON.Scene to append to
  67702. * @param onProgress a callback with a progress event for each file being loaded
  67703. * @param pluginExtension the extension used to determine the plugin
  67704. * @returns The loaded asset container
  67705. */
  67706. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67707. if (sceneFilename === void 0) { sceneFilename = ""; }
  67708. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67709. if (onProgress === void 0) { onProgress = null; }
  67710. if (pluginExtension === void 0) { pluginExtension = null; }
  67711. return new Promise(function (resolve, reject) {
  67712. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67713. resolve(assetContainer);
  67714. }, onProgress, function (scene, message, exception) {
  67715. reject(exception || new Error(message));
  67716. }, pluginExtension);
  67717. });
  67718. };
  67719. // Flags
  67720. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67721. SceneLoader._ShowLoadingScreen = true;
  67722. SceneLoader._CleanBoneMatrixWeights = false;
  67723. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67724. // Members
  67725. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67726. SceneLoader._registeredPlugins = {};
  67727. return SceneLoader;
  67728. }());
  67729. BABYLON.SceneLoader = SceneLoader;
  67730. ;
  67731. })(BABYLON || (BABYLON = {}));
  67732. //# sourceMappingURL=babylon.sceneLoader.js.map
  67733. var BABYLON;
  67734. (function (BABYLON) {
  67735. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67736. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67737. var parsedMaterial = parsedData.materials[index];
  67738. if (parsedMaterial.id === id) {
  67739. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67740. }
  67741. }
  67742. return null;
  67743. };
  67744. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67745. for (var i in names) {
  67746. if (mesh.name === names[i]) {
  67747. hierarchyIds.push(mesh.id);
  67748. return true;
  67749. }
  67750. }
  67751. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67752. hierarchyIds.push(mesh.id);
  67753. return true;
  67754. }
  67755. return false;
  67756. };
  67757. var logOperation = function (operation, producer) {
  67758. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67759. };
  67760. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67761. if (addToScene === void 0) { addToScene = false; }
  67762. var container = new BABYLON.AssetContainer(scene);
  67763. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67764. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67765. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67766. // and avoid problems with multiple concurrent .babylon loads.
  67767. var log = "importScene has failed JSON parse";
  67768. try {
  67769. var parsedData = JSON.parse(data);
  67770. log = "";
  67771. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67772. var index;
  67773. var cache;
  67774. // Lights
  67775. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67776. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67777. var parsedLight = parsedData.lights[index];
  67778. var light = BABYLON.Light.Parse(parsedLight, scene);
  67779. if (light) {
  67780. container.lights.push(light);
  67781. log += (index === 0 ? "\n\tLights:" : "");
  67782. log += "\n\t\t" + light.toString(fullDetails);
  67783. }
  67784. }
  67785. }
  67786. // Animations
  67787. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67788. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67789. var parsedAnimation = parsedData.animations[index];
  67790. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67791. scene.animations.push(animation);
  67792. container.animations.push(animation);
  67793. log += (index === 0 ? "\n\tAnimations:" : "");
  67794. log += "\n\t\t" + animation.toString(fullDetails);
  67795. }
  67796. }
  67797. // Materials
  67798. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67799. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67800. var parsedMaterial = parsedData.materials[index];
  67801. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67802. container.materials.push(mat);
  67803. log += (index === 0 ? "\n\tMaterials:" : "");
  67804. log += "\n\t\t" + mat.toString(fullDetails);
  67805. }
  67806. }
  67807. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67808. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67809. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67810. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67811. container.multiMaterials.push(mmat);
  67812. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67813. log += "\n\t\t" + mmat.toString(fullDetails);
  67814. }
  67815. }
  67816. // Morph targets
  67817. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67818. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67819. var managerData = _a[_i];
  67820. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67821. }
  67822. }
  67823. // Skeletons
  67824. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67825. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67826. var parsedSkeleton = parsedData.skeletons[index];
  67827. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67828. container.skeletons.push(skeleton);
  67829. log += (index === 0 ? "\n\tSkeletons:" : "");
  67830. log += "\n\t\t" + skeleton.toString(fullDetails);
  67831. }
  67832. }
  67833. // Geometries
  67834. var geometries = parsedData.geometries;
  67835. if (geometries !== undefined && geometries !== null) {
  67836. var addedGeometry = new Array();
  67837. // Boxes
  67838. var boxes = geometries.boxes;
  67839. if (boxes !== undefined && boxes !== null) {
  67840. for (index = 0, cache = boxes.length; index < cache; index++) {
  67841. var parsedBox = boxes[index];
  67842. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67843. }
  67844. }
  67845. // Spheres
  67846. var spheres = geometries.spheres;
  67847. if (spheres !== undefined && spheres !== null) {
  67848. for (index = 0, cache = spheres.length; index < cache; index++) {
  67849. var parsedSphere = spheres[index];
  67850. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67851. }
  67852. }
  67853. // Cylinders
  67854. var cylinders = geometries.cylinders;
  67855. if (cylinders !== undefined && cylinders !== null) {
  67856. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67857. var parsedCylinder = cylinders[index];
  67858. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67859. }
  67860. }
  67861. // Toruses
  67862. var toruses = geometries.toruses;
  67863. if (toruses !== undefined && toruses !== null) {
  67864. for (index = 0, cache = toruses.length; index < cache; index++) {
  67865. var parsedTorus = toruses[index];
  67866. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67867. }
  67868. }
  67869. // Grounds
  67870. var grounds = geometries.grounds;
  67871. if (grounds !== undefined && grounds !== null) {
  67872. for (index = 0, cache = grounds.length; index < cache; index++) {
  67873. var parsedGround = grounds[index];
  67874. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67875. }
  67876. }
  67877. // Planes
  67878. var planes = geometries.planes;
  67879. if (planes !== undefined && planes !== null) {
  67880. for (index = 0, cache = planes.length; index < cache; index++) {
  67881. var parsedPlane = planes[index];
  67882. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67883. }
  67884. }
  67885. // TorusKnots
  67886. var torusKnots = geometries.torusKnots;
  67887. if (torusKnots !== undefined && torusKnots !== null) {
  67888. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67889. var parsedTorusKnot = torusKnots[index];
  67890. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67891. }
  67892. }
  67893. // VertexData
  67894. var vertexData = geometries.vertexData;
  67895. if (vertexData !== undefined && vertexData !== null) {
  67896. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67897. var parsedVertexData = vertexData[index];
  67898. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67899. }
  67900. }
  67901. addedGeometry.forEach(function (g) {
  67902. if (g) {
  67903. container.geometries.push(g);
  67904. }
  67905. });
  67906. }
  67907. // Transform nodes
  67908. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67909. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67910. var parsedTransformNode = parsedData.transformNodes[index];
  67911. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67912. container.transformNodes.push(node);
  67913. }
  67914. }
  67915. // Meshes
  67916. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67917. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67918. var parsedMesh = parsedData.meshes[index];
  67919. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67920. container.meshes.push(mesh);
  67921. log += (index === 0 ? "\n\tMeshes:" : "");
  67922. log += "\n\t\t" + mesh.toString(fullDetails);
  67923. }
  67924. }
  67925. // Cameras
  67926. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67927. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67928. var parsedCamera = parsedData.cameras[index];
  67929. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67930. container.cameras.push(camera);
  67931. log += (index === 0 ? "\n\tCameras:" : "");
  67932. log += "\n\t\t" + camera.toString(fullDetails);
  67933. }
  67934. }
  67935. // Browsing all the graph to connect the dots
  67936. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67937. var camera = scene.cameras[index];
  67938. if (camera._waitingParentId) {
  67939. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67940. camera._waitingParentId = null;
  67941. }
  67942. }
  67943. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67944. var light_1 = scene.lights[index];
  67945. if (light_1 && light_1._waitingParentId) {
  67946. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67947. light_1._waitingParentId = null;
  67948. }
  67949. }
  67950. // Sounds
  67951. // TODO: add sound
  67952. var loadedSounds = [];
  67953. var loadedSound;
  67954. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67955. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67956. var parsedSound = parsedData.sounds[index];
  67957. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67958. if (!parsedSound.url)
  67959. parsedSound.url = parsedSound.name;
  67960. if (!loadedSounds[parsedSound.url]) {
  67961. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67962. loadedSounds[parsedSound.url] = loadedSound;
  67963. container.sounds.push(loadedSound);
  67964. }
  67965. else {
  67966. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67967. }
  67968. }
  67969. else {
  67970. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67971. }
  67972. }
  67973. }
  67974. loadedSounds = [];
  67975. // Connect parents & children and parse actions
  67976. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67977. var transformNode = scene.transformNodes[index];
  67978. if (transformNode._waitingParentId) {
  67979. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67980. transformNode._waitingParentId = null;
  67981. }
  67982. }
  67983. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67984. var mesh = scene.meshes[index];
  67985. if (mesh._waitingParentId) {
  67986. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67987. mesh._waitingParentId = null;
  67988. }
  67989. if (mesh._waitingActions) {
  67990. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67991. mesh._waitingActions = null;
  67992. }
  67993. }
  67994. // freeze world matrix application
  67995. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67996. var currentMesh = scene.meshes[index];
  67997. if (currentMesh._waitingFreezeWorldMatrix) {
  67998. currentMesh.freezeWorldMatrix();
  67999. currentMesh._waitingFreezeWorldMatrix = null;
  68000. }
  68001. else {
  68002. currentMesh.computeWorldMatrix(true);
  68003. }
  68004. }
  68005. // Particles Systems
  68006. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68007. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68008. var parsedParticleSystem = parsedData.particleSystems[index];
  68009. if (parsedParticleSystem.activeParticleCount) {
  68010. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68011. container.particleSystems.push(ps);
  68012. }
  68013. else {
  68014. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68015. container.particleSystems.push(ps);
  68016. }
  68017. }
  68018. }
  68019. // Lens flares
  68020. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68021. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68022. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68023. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68024. container.lensFlareSystems.push(lf);
  68025. }
  68026. }
  68027. // Shadows
  68028. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68029. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68030. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68031. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68032. container.shadowGenerators.push(sg);
  68033. }
  68034. }
  68035. // Lights exclusions / inclusions
  68036. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68037. var light_2 = scene.lights[index];
  68038. // Excluded check
  68039. if (light_2._excludedMeshesIds.length > 0) {
  68040. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68041. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68042. if (excludedMesh) {
  68043. light_2.excludedMeshes.push(excludedMesh);
  68044. }
  68045. }
  68046. light_2._excludedMeshesIds = [];
  68047. }
  68048. // Included check
  68049. if (light_2._includedOnlyMeshesIds.length > 0) {
  68050. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68051. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68052. if (includedOnlyMesh) {
  68053. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68054. }
  68055. }
  68056. light_2._includedOnlyMeshesIds = [];
  68057. }
  68058. }
  68059. // Effect layers
  68060. if (parsedData.effectLayers) {
  68061. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68062. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68063. container.effectLayers.push(effectLayer);
  68064. }
  68065. }
  68066. // Actions (scene)
  68067. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68068. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68069. }
  68070. if (!addToScene) {
  68071. container.removeAllFromScene();
  68072. }
  68073. }
  68074. catch (err) {
  68075. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68076. if (onError) {
  68077. onError(msg, err);
  68078. }
  68079. else {
  68080. BABYLON.Tools.Log(msg);
  68081. throw err;
  68082. }
  68083. }
  68084. finally {
  68085. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68086. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68087. }
  68088. }
  68089. return container;
  68090. };
  68091. BABYLON.SceneLoader.RegisterPlugin({
  68092. name: "babylon.js",
  68093. extensions: ".babylon",
  68094. canDirectLoad: function (data) {
  68095. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68096. return true;
  68097. }
  68098. return false;
  68099. },
  68100. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68101. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68102. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68103. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68104. // and avoid problems with multiple concurrent .babylon loads.
  68105. var log = "importMesh has failed JSON parse";
  68106. try {
  68107. var parsedData = JSON.parse(data);
  68108. log = "";
  68109. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68110. if (!meshesNames) {
  68111. meshesNames = null;
  68112. }
  68113. else if (!Array.isArray(meshesNames)) {
  68114. meshesNames = [meshesNames];
  68115. }
  68116. var hierarchyIds = new Array();
  68117. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68118. var loadedSkeletonsIds = [];
  68119. var loadedMaterialsIds = [];
  68120. var index;
  68121. var cache;
  68122. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68123. var parsedMesh = parsedData.meshes[index];
  68124. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68125. if (meshesNames !== null) {
  68126. // Remove found mesh name from list.
  68127. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68128. }
  68129. //Geometry?
  68130. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68131. //does the file contain geometries?
  68132. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68133. //find the correct geometry and add it to the scene
  68134. var found = false;
  68135. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68136. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68137. return;
  68138. }
  68139. else {
  68140. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68141. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68142. switch (geometryType) {
  68143. case "boxes":
  68144. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68145. break;
  68146. case "spheres":
  68147. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68148. break;
  68149. case "cylinders":
  68150. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68151. break;
  68152. case "toruses":
  68153. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68154. break;
  68155. case "grounds":
  68156. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68157. break;
  68158. case "planes":
  68159. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68160. break;
  68161. case "torusKnots":
  68162. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68163. break;
  68164. case "vertexData":
  68165. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68166. break;
  68167. }
  68168. found = true;
  68169. }
  68170. });
  68171. }
  68172. });
  68173. if (found === false) {
  68174. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68175. }
  68176. }
  68177. }
  68178. // Material ?
  68179. if (parsedMesh.materialId) {
  68180. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68181. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68182. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68183. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68184. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68185. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68186. var subMatId = parsedMultiMaterial.materials[matIndex];
  68187. loadedMaterialsIds.push(subMatId);
  68188. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68189. if (mat) {
  68190. log += "\n\tMaterial " + mat.toString(fullDetails);
  68191. }
  68192. }
  68193. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68194. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68195. if (mmat) {
  68196. materialFound = true;
  68197. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68198. }
  68199. break;
  68200. }
  68201. }
  68202. }
  68203. if (materialFound === false) {
  68204. loadedMaterialsIds.push(parsedMesh.materialId);
  68205. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68206. if (!mat) {
  68207. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68208. }
  68209. else {
  68210. log += "\n\tMaterial " + mat.toString(fullDetails);
  68211. }
  68212. }
  68213. }
  68214. // Skeleton ?
  68215. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68216. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68217. if (skeletonAlreadyLoaded === false) {
  68218. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68219. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68220. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68221. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68222. skeletons.push(skeleton);
  68223. loadedSkeletonsIds.push(parsedSkeleton.id);
  68224. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68225. }
  68226. }
  68227. }
  68228. }
  68229. // Morph targets ?
  68230. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68231. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68232. var managerData = _a[_i];
  68233. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68234. }
  68235. }
  68236. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68237. meshes.push(mesh);
  68238. log += "\n\tMesh " + mesh.toString(fullDetails);
  68239. }
  68240. }
  68241. // Connecting parents
  68242. var currentMesh;
  68243. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68244. currentMesh = scene.meshes[index];
  68245. if (currentMesh._waitingParentId) {
  68246. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68247. currentMesh._waitingParentId = null;
  68248. }
  68249. }
  68250. // freeze and compute world matrix application
  68251. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68252. currentMesh = scene.meshes[index];
  68253. if (currentMesh._waitingFreezeWorldMatrix) {
  68254. currentMesh.freezeWorldMatrix();
  68255. currentMesh._waitingFreezeWorldMatrix = null;
  68256. }
  68257. else {
  68258. currentMesh.computeWorldMatrix(true);
  68259. }
  68260. }
  68261. }
  68262. // Particles
  68263. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68264. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68265. var parsedParticleSystem = parsedData.particleSystems[index];
  68266. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68267. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68268. }
  68269. }
  68270. }
  68271. return true;
  68272. }
  68273. catch (err) {
  68274. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68275. if (onError) {
  68276. onError(msg, err);
  68277. }
  68278. else {
  68279. BABYLON.Tools.Log(msg);
  68280. throw err;
  68281. }
  68282. }
  68283. finally {
  68284. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68285. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68286. }
  68287. }
  68288. return false;
  68289. },
  68290. load: function (scene, data, rootUrl, onError) {
  68291. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68292. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68293. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68294. // and avoid problems with multiple concurrent .babylon loads.
  68295. var log = "importScene has failed JSON parse";
  68296. try {
  68297. var parsedData = JSON.parse(data);
  68298. log = "";
  68299. // Scene
  68300. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68301. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68302. }
  68303. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68304. scene.autoClear = parsedData.autoClear;
  68305. }
  68306. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68307. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68308. }
  68309. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68310. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68311. }
  68312. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68313. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68314. }
  68315. // Fog
  68316. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68317. scene.fogMode = parsedData.fogMode;
  68318. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68319. scene.fogStart = parsedData.fogStart;
  68320. scene.fogEnd = parsedData.fogEnd;
  68321. scene.fogDensity = parsedData.fogDensity;
  68322. log += "\tFog mode for scene: ";
  68323. switch (scene.fogMode) {
  68324. // getters not compiling, so using hardcoded
  68325. case 1:
  68326. log += "exp\n";
  68327. break;
  68328. case 2:
  68329. log += "exp2\n";
  68330. break;
  68331. case 3:
  68332. log += "linear\n";
  68333. break;
  68334. }
  68335. }
  68336. //Physics
  68337. if (parsedData.physicsEnabled) {
  68338. var physicsPlugin;
  68339. if (parsedData.physicsEngine === "cannon") {
  68340. physicsPlugin = new BABYLON.CannonJSPlugin();
  68341. }
  68342. else if (parsedData.physicsEngine === "oimo") {
  68343. physicsPlugin = new BABYLON.OimoJSPlugin();
  68344. }
  68345. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68346. //else - default engine, which is currently oimo
  68347. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68348. scene.enablePhysics(physicsGravity, physicsPlugin);
  68349. }
  68350. // Metadata
  68351. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68352. scene.metadata = parsedData.metadata;
  68353. }
  68354. //collisions, if defined. otherwise, default is true
  68355. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68356. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68357. }
  68358. scene.workerCollisions = !!parsedData.workerCollisions;
  68359. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68360. if (!container) {
  68361. return false;
  68362. }
  68363. if (parsedData.autoAnimate) {
  68364. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68365. }
  68366. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68367. scene.setActiveCameraByID(parsedData.activeCameraID);
  68368. }
  68369. // Environment texture
  68370. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68371. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68372. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68373. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68374. if (parsedData.environmentTextureRotationY) {
  68375. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68376. }
  68377. scene.environmentTexture = hdrTexture;
  68378. }
  68379. else {
  68380. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68381. if (parsedData.environmentTextureRotationY) {
  68382. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68383. }
  68384. scene.environmentTexture = cubeTexture;
  68385. }
  68386. if (parsedData.createDefaultSkybox === true) {
  68387. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68388. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68389. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68390. }
  68391. }
  68392. // Finish
  68393. return true;
  68394. }
  68395. catch (err) {
  68396. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68397. if (onError) {
  68398. onError(msg, err);
  68399. }
  68400. else {
  68401. BABYLON.Tools.Log(msg);
  68402. throw err;
  68403. }
  68404. }
  68405. finally {
  68406. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68407. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68408. }
  68409. }
  68410. return false;
  68411. },
  68412. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68413. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68414. return container;
  68415. }
  68416. });
  68417. })(BABYLON || (BABYLON = {}));
  68418. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68419. var BABYLON;
  68420. (function (BABYLON) {
  68421. var FilesInput = /** @class */ (function () {
  68422. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68423. this.onProcessFileCallback = function () { return true; };
  68424. this._engine = engine;
  68425. this._currentScene = scene;
  68426. this._sceneLoadedCallback = sceneLoadedCallback;
  68427. this._progressCallback = progressCallback;
  68428. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68429. this._textureLoadingCallback = textureLoadingCallback;
  68430. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68431. this._onReloadCallback = onReloadCallback;
  68432. this._errorCallback = errorCallback;
  68433. }
  68434. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68435. var _this = this;
  68436. if (elementToMonitor) {
  68437. this._elementToMonitor = elementToMonitor;
  68438. this._dragEnterHandler = function (e) { _this.drag(e); };
  68439. this._dragOverHandler = function (e) { _this.drag(e); };
  68440. this._dropHandler = function (e) { _this.drop(e); };
  68441. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68442. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68443. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68444. }
  68445. };
  68446. FilesInput.prototype.dispose = function () {
  68447. if (!this._elementToMonitor) {
  68448. return;
  68449. }
  68450. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68451. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68452. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68453. };
  68454. FilesInput.prototype.renderFunction = function () {
  68455. if (this._additionalRenderLoopLogicCallback) {
  68456. this._additionalRenderLoopLogicCallback();
  68457. }
  68458. if (this._currentScene) {
  68459. if (this._textureLoadingCallback) {
  68460. var remaining = this._currentScene.getWaitingItemsCount();
  68461. if (remaining > 0) {
  68462. this._textureLoadingCallback(remaining);
  68463. }
  68464. }
  68465. this._currentScene.render();
  68466. }
  68467. };
  68468. FilesInput.prototype.drag = function (e) {
  68469. e.stopPropagation();
  68470. e.preventDefault();
  68471. };
  68472. FilesInput.prototype.drop = function (eventDrop) {
  68473. eventDrop.stopPropagation();
  68474. eventDrop.preventDefault();
  68475. this.loadFiles(eventDrop);
  68476. };
  68477. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68478. var _this = this;
  68479. var reader = folder.createReader();
  68480. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68481. reader.readEntries(function (entries) {
  68482. remaining.count += entries.length;
  68483. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68484. var entry = entries_1[_i];
  68485. if (entry.isFile) {
  68486. entry.file(function (file) {
  68487. file.correctName = relativePath + file.name;
  68488. files.push(file);
  68489. if (--remaining.count === 0) {
  68490. callback();
  68491. }
  68492. });
  68493. }
  68494. else if (entry.isDirectory) {
  68495. _this._traverseFolder(entry, files, remaining, callback);
  68496. }
  68497. }
  68498. if (--remaining.count) {
  68499. callback();
  68500. }
  68501. });
  68502. };
  68503. FilesInput.prototype._processFiles = function (files) {
  68504. for (var i = 0; i < files.length; i++) {
  68505. var name = files[i].correctName.toLowerCase();
  68506. var extension = name.split('.').pop();
  68507. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68508. continue;
  68509. }
  68510. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68511. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68512. this._sceneFileToLoad = files[i];
  68513. }
  68514. else {
  68515. FilesInput.FilesToLoad[name] = files[i];
  68516. }
  68517. }
  68518. };
  68519. FilesInput.prototype.loadFiles = function (event) {
  68520. var _this = this;
  68521. if (this._startingProcessingFilesCallback)
  68522. this._startingProcessingFilesCallback();
  68523. // Handling data transfer via drag'n'drop
  68524. if (event && event.dataTransfer && event.dataTransfer.files) {
  68525. this._filesToLoad = event.dataTransfer.files;
  68526. }
  68527. // Handling files from input files
  68528. if (event && event.target && event.target.files) {
  68529. this._filesToLoad = event.target.files;
  68530. }
  68531. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68532. var files_1 = new Array();
  68533. var folders = [];
  68534. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68535. for (var i = 0; i < this._filesToLoad.length; i++) {
  68536. var fileToLoad = this._filesToLoad[i];
  68537. var name_1 = fileToLoad.name.toLowerCase();
  68538. var entry = void 0;
  68539. fileToLoad.correctName = name_1;
  68540. if (items) {
  68541. var item = items[i];
  68542. if (item.getAsEntry) {
  68543. entry = item.getAsEntry();
  68544. }
  68545. else if (item.webkitGetAsEntry) {
  68546. entry = item.webkitGetAsEntry();
  68547. }
  68548. }
  68549. if (!entry) {
  68550. files_1.push(fileToLoad);
  68551. }
  68552. else {
  68553. if (entry.isDirectory) {
  68554. folders.push(entry);
  68555. }
  68556. else {
  68557. files_1.push(fileToLoad);
  68558. }
  68559. }
  68560. }
  68561. if (folders.length === 0) {
  68562. this._processFiles(files_1);
  68563. this._processReload();
  68564. }
  68565. else {
  68566. var remaining = { count: folders.length };
  68567. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68568. var folder = folders_1[_i];
  68569. this._traverseFolder(folder, files_1, remaining, function () {
  68570. _this._processFiles(files_1);
  68571. if (remaining.count === 0) {
  68572. _this._processReload();
  68573. }
  68574. });
  68575. }
  68576. }
  68577. }
  68578. };
  68579. FilesInput.prototype._processReload = function () {
  68580. if (this._onReloadCallback) {
  68581. this._onReloadCallback(this._sceneFileToLoad);
  68582. }
  68583. else {
  68584. this.reload();
  68585. }
  68586. };
  68587. FilesInput.prototype.reload = function () {
  68588. var _this = this;
  68589. // If a scene file has been provided
  68590. if (this._sceneFileToLoad) {
  68591. if (this._currentScene) {
  68592. if (BABYLON.Tools.errorsCount > 0) {
  68593. BABYLON.Tools.ClearLogCache();
  68594. }
  68595. this._engine.stopRenderLoop();
  68596. }
  68597. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68598. if (_this._progressCallback) {
  68599. _this._progressCallback(progress);
  68600. }
  68601. }).then(function (scene) {
  68602. if (_this._currentScene) {
  68603. _this._currentScene.dispose();
  68604. }
  68605. _this._currentScene = scene;
  68606. if (_this._sceneLoadedCallback) {
  68607. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68608. }
  68609. // Wait for textures and shaders to be ready
  68610. _this._currentScene.executeWhenReady(function () {
  68611. _this._engine.runRenderLoop(function () {
  68612. _this.renderFunction();
  68613. });
  68614. });
  68615. }).catch(function (error) {
  68616. if (_this._errorCallback) {
  68617. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68618. }
  68619. });
  68620. }
  68621. else {
  68622. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68623. }
  68624. };
  68625. FilesInput.FilesToLoad = {};
  68626. return FilesInput;
  68627. }());
  68628. BABYLON.FilesInput = FilesInput;
  68629. })(BABYLON || (BABYLON = {}));
  68630. //# sourceMappingURL=babylon.filesInput.js.map
  68631. var BABYLON;
  68632. (function (BABYLON) {
  68633. /**
  68634. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68635. * The underlying implementation relies on an associative array to ensure the best performances.
  68636. * The value can be anything including 'null' but except 'undefined'
  68637. */
  68638. var StringDictionary = /** @class */ (function () {
  68639. function StringDictionary() {
  68640. this._count = 0;
  68641. this._data = {};
  68642. }
  68643. /**
  68644. * This will clear this dictionary and copy the content from the 'source' one.
  68645. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68646. * @param source the dictionary to take the content from and copy to this dictionary
  68647. */
  68648. StringDictionary.prototype.copyFrom = function (source) {
  68649. var _this = this;
  68650. this.clear();
  68651. source.forEach(function (t, v) { return _this.add(t, v); });
  68652. };
  68653. /**
  68654. * Get a value based from its key
  68655. * @param key the given key to get the matching value from
  68656. * @return the value if found, otherwise undefined is returned
  68657. */
  68658. StringDictionary.prototype.get = function (key) {
  68659. var val = this._data[key];
  68660. if (val !== undefined) {
  68661. return val;
  68662. }
  68663. return undefined;
  68664. };
  68665. /**
  68666. * Get a value from its key or add it if it doesn't exist.
  68667. * This method will ensure you that a given key/data will be present in the dictionary.
  68668. * @param key the given key to get the matching value from
  68669. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68670. * The factory will only be invoked if there's no data for the given key.
  68671. * @return the value corresponding to the key.
  68672. */
  68673. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68674. var val = this.get(key);
  68675. if (val !== undefined) {
  68676. return val;
  68677. }
  68678. val = factory(key);
  68679. if (val) {
  68680. this.add(key, val);
  68681. }
  68682. return val;
  68683. };
  68684. /**
  68685. * Get a value from its key if present in the dictionary otherwise add it
  68686. * @param key the key to get the value from
  68687. * @param val if there's no such key/value pair in the dictionary add it with this value
  68688. * @return the value corresponding to the key
  68689. */
  68690. StringDictionary.prototype.getOrAdd = function (key, val) {
  68691. var curVal = this.get(key);
  68692. if (curVal !== undefined) {
  68693. return curVal;
  68694. }
  68695. this.add(key, val);
  68696. return val;
  68697. };
  68698. /**
  68699. * Check if there's a given key in the dictionary
  68700. * @param key the key to check for
  68701. * @return true if the key is present, false otherwise
  68702. */
  68703. StringDictionary.prototype.contains = function (key) {
  68704. return this._data[key] !== undefined;
  68705. };
  68706. /**
  68707. * Add a new key and its corresponding value
  68708. * @param key the key to add
  68709. * @param value the value corresponding to the key
  68710. * @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
  68711. */
  68712. StringDictionary.prototype.add = function (key, value) {
  68713. if (this._data[key] !== undefined) {
  68714. return false;
  68715. }
  68716. this._data[key] = value;
  68717. ++this._count;
  68718. return true;
  68719. };
  68720. StringDictionary.prototype.set = function (key, value) {
  68721. if (this._data[key] === undefined) {
  68722. return false;
  68723. }
  68724. this._data[key] = value;
  68725. return true;
  68726. };
  68727. /**
  68728. * Get the element of the given key and remove it from the dictionary
  68729. * @param key
  68730. */
  68731. StringDictionary.prototype.getAndRemove = function (key) {
  68732. var val = this.get(key);
  68733. if (val !== undefined) {
  68734. delete this._data[key];
  68735. --this._count;
  68736. return val;
  68737. }
  68738. return null;
  68739. };
  68740. /**
  68741. * Remove a key/value from the dictionary.
  68742. * @param key the key to remove
  68743. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68744. */
  68745. StringDictionary.prototype.remove = function (key) {
  68746. if (this.contains(key)) {
  68747. delete this._data[key];
  68748. --this._count;
  68749. return true;
  68750. }
  68751. return false;
  68752. };
  68753. /**
  68754. * Clear the whole content of the dictionary
  68755. */
  68756. StringDictionary.prototype.clear = function () {
  68757. this._data = {};
  68758. this._count = 0;
  68759. };
  68760. Object.defineProperty(StringDictionary.prototype, "count", {
  68761. get: function () {
  68762. return this._count;
  68763. },
  68764. enumerable: true,
  68765. configurable: true
  68766. });
  68767. /**
  68768. * Execute a callback on each key/val of the dictionary.
  68769. * Note that you can remove any element in this dictionary in the callback implementation
  68770. * @param callback the callback to execute on a given key/value pair
  68771. */
  68772. StringDictionary.prototype.forEach = function (callback) {
  68773. for (var cur in this._data) {
  68774. var val = this._data[cur];
  68775. callback(cur, val);
  68776. }
  68777. };
  68778. /**
  68779. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68780. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68781. * Note that you can remove any element in this dictionary in the callback implementation
  68782. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68783. */
  68784. StringDictionary.prototype.first = function (callback) {
  68785. for (var cur in this._data) {
  68786. var val = this._data[cur];
  68787. var res = callback(cur, val);
  68788. if (res) {
  68789. return res;
  68790. }
  68791. }
  68792. return null;
  68793. };
  68794. return StringDictionary;
  68795. }());
  68796. BABYLON.StringDictionary = StringDictionary;
  68797. })(BABYLON || (BABYLON = {}));
  68798. //# sourceMappingURL=babylon.stringDictionary.js.map
  68799. var BABYLON;
  68800. (function (BABYLON) {
  68801. var Tags = /** @class */ (function () {
  68802. function Tags() {
  68803. }
  68804. Tags.EnableFor = function (obj) {
  68805. obj._tags = obj._tags || {};
  68806. obj.hasTags = function () {
  68807. return Tags.HasTags(obj);
  68808. };
  68809. obj.addTags = function (tagsString) {
  68810. return Tags.AddTagsTo(obj, tagsString);
  68811. };
  68812. obj.removeTags = function (tagsString) {
  68813. return Tags.RemoveTagsFrom(obj, tagsString);
  68814. };
  68815. obj.matchesTagsQuery = function (tagsQuery) {
  68816. return Tags.MatchesQuery(obj, tagsQuery);
  68817. };
  68818. };
  68819. Tags.DisableFor = function (obj) {
  68820. delete obj._tags;
  68821. delete obj.hasTags;
  68822. delete obj.addTags;
  68823. delete obj.removeTags;
  68824. delete obj.matchesTagsQuery;
  68825. };
  68826. Tags.HasTags = function (obj) {
  68827. if (!obj._tags) {
  68828. return false;
  68829. }
  68830. return !BABYLON.Tools.IsEmpty(obj._tags);
  68831. };
  68832. Tags.GetTags = function (obj, asString) {
  68833. if (asString === void 0) { asString = true; }
  68834. if (!obj._tags) {
  68835. return null;
  68836. }
  68837. if (asString) {
  68838. var tagsArray = [];
  68839. for (var tag in obj._tags) {
  68840. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68841. tagsArray.push(tag);
  68842. }
  68843. }
  68844. return tagsArray.join(" ");
  68845. }
  68846. else {
  68847. return obj._tags;
  68848. }
  68849. };
  68850. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68851. // a tag cannot start with '||', '&&', and '!'
  68852. // it cannot contain whitespaces
  68853. Tags.AddTagsTo = function (obj, tagsString) {
  68854. if (!tagsString) {
  68855. return;
  68856. }
  68857. if (typeof tagsString !== "string") {
  68858. return;
  68859. }
  68860. var tags = tagsString.split(" ");
  68861. tags.forEach(function (tag, index, array) {
  68862. Tags._AddTagTo(obj, tag);
  68863. });
  68864. };
  68865. Tags._AddTagTo = function (obj, tag) {
  68866. tag = tag.trim();
  68867. if (tag === "" || tag === "true" || tag === "false") {
  68868. return;
  68869. }
  68870. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68871. return;
  68872. }
  68873. Tags.EnableFor(obj);
  68874. obj._tags[tag] = true;
  68875. };
  68876. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68877. if (!Tags.HasTags(obj)) {
  68878. return;
  68879. }
  68880. var tags = tagsString.split(" ");
  68881. for (var t in tags) {
  68882. Tags._RemoveTagFrom(obj, tags[t]);
  68883. }
  68884. };
  68885. Tags._RemoveTagFrom = function (obj, tag) {
  68886. delete obj._tags[tag];
  68887. };
  68888. Tags.MatchesQuery = function (obj, tagsQuery) {
  68889. if (tagsQuery === undefined) {
  68890. return true;
  68891. }
  68892. if (tagsQuery === "") {
  68893. return Tags.HasTags(obj);
  68894. }
  68895. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68896. };
  68897. return Tags;
  68898. }());
  68899. BABYLON.Tags = Tags;
  68900. })(BABYLON || (BABYLON = {}));
  68901. //# sourceMappingURL=babylon.tags.js.map
  68902. var BABYLON;
  68903. (function (BABYLON) {
  68904. /**
  68905. * Class used to evalaute queries containing `and` and `or` operators
  68906. */
  68907. var AndOrNotEvaluator = /** @class */ (function () {
  68908. function AndOrNotEvaluator() {
  68909. }
  68910. /**
  68911. * Evaluate a query
  68912. * @param query defines the query to evaluate
  68913. * @param evaluateCallback defines the callback used to filter result
  68914. * @returns true if the query matches
  68915. */
  68916. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68917. if (!query.match(/\([^\(\)]*\)/g)) {
  68918. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68919. }
  68920. else {
  68921. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68922. // remove parenthesis
  68923. r = r.slice(1, r.length - 1);
  68924. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68925. });
  68926. }
  68927. if (query === "true") {
  68928. return true;
  68929. }
  68930. if (query === "false") {
  68931. return false;
  68932. }
  68933. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68934. };
  68935. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68936. evaluateCallback = evaluateCallback || (function (r) {
  68937. return r === "true" ? true : false;
  68938. });
  68939. var result;
  68940. var or = parenthesisContent.split("||");
  68941. for (var i in or) {
  68942. if (or.hasOwnProperty(i)) {
  68943. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68944. var and = ori.split("&&");
  68945. if (and.length > 1) {
  68946. for (var j = 0; j < and.length; ++j) {
  68947. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68948. if (andj !== "true" && andj !== "false") {
  68949. if (andj[0] === "!") {
  68950. result = !evaluateCallback(andj.substring(1));
  68951. }
  68952. else {
  68953. result = evaluateCallback(andj);
  68954. }
  68955. }
  68956. else {
  68957. result = andj === "true" ? true : false;
  68958. }
  68959. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68960. ori = "false";
  68961. break;
  68962. }
  68963. }
  68964. }
  68965. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68966. result = true;
  68967. break;
  68968. }
  68969. // result equals false (or undefined)
  68970. if (ori !== "true" && ori !== "false") {
  68971. if (ori[0] === "!") {
  68972. result = !evaluateCallback(ori.substring(1));
  68973. }
  68974. else {
  68975. result = evaluateCallback(ori);
  68976. }
  68977. }
  68978. else {
  68979. result = ori === "true" ? true : false;
  68980. }
  68981. }
  68982. }
  68983. // the whole parenthesis scope is replaced by 'true' or 'false'
  68984. return result ? "true" : "false";
  68985. };
  68986. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68987. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68988. // remove whitespaces
  68989. r = r.replace(/[\s]/g, function () { return ""; });
  68990. return r.length % 2 ? "!" : "";
  68991. });
  68992. booleanString = booleanString.trim();
  68993. if (booleanString === "!true") {
  68994. booleanString = "false";
  68995. }
  68996. else if (booleanString === "!false") {
  68997. booleanString = "true";
  68998. }
  68999. return booleanString;
  69000. };
  69001. return AndOrNotEvaluator;
  69002. }());
  69003. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69004. })(BABYLON || (BABYLON = {}));
  69005. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69006. var BABYLON;
  69007. (function (BABYLON) {
  69008. /**
  69009. * Class used to enable access to IndexedDB
  69010. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69011. */
  69012. var Database = /** @class */ (function () {
  69013. /**
  69014. * Creates a new Database
  69015. * @param urlToScene defines the url to load the scene
  69016. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69017. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69018. */
  69019. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69020. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69021. var _this = this;
  69022. // Handling various flavors of prefixed version of IndexedDB
  69023. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69024. this.callbackManifestChecked = callbackManifestChecked;
  69025. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69026. this.db = null;
  69027. this._enableSceneOffline = false;
  69028. this._enableTexturesOffline = false;
  69029. this.manifestVersionFound = 0;
  69030. this.mustUpdateRessources = false;
  69031. this.hasReachedQuota = false;
  69032. if (!Database.IDBStorageEnabled) {
  69033. this.callbackManifestChecked(true);
  69034. }
  69035. else {
  69036. if (disableManifestCheck) {
  69037. this._enableSceneOffline = true;
  69038. this._enableTexturesOffline = true;
  69039. this.manifestVersionFound = 1;
  69040. BABYLON.Tools.SetImmediate(function () {
  69041. _this.callbackManifestChecked(true);
  69042. });
  69043. }
  69044. else {
  69045. this._checkManifestFile();
  69046. }
  69047. }
  69048. }
  69049. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69050. /**
  69051. * Gets a boolean indicating if scene must be saved in the database
  69052. */
  69053. get: function () {
  69054. return this._enableSceneOffline;
  69055. },
  69056. enumerable: true,
  69057. configurable: true
  69058. });
  69059. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69060. /**
  69061. * Gets a boolean indicating if textures must be saved in the database
  69062. */
  69063. get: function () {
  69064. return this._enableTexturesOffline;
  69065. },
  69066. enumerable: true,
  69067. configurable: true
  69068. });
  69069. Database.prototype._checkManifestFile = function () {
  69070. var _this = this;
  69071. var noManifestFile = function () {
  69072. _this._enableSceneOffline = false;
  69073. _this._enableTexturesOffline = false;
  69074. _this.callbackManifestChecked(false);
  69075. };
  69076. var timeStampUsed = false;
  69077. var manifestURL = this.currentSceneUrl + ".manifest";
  69078. var xhr = new XMLHttpRequest();
  69079. if (navigator.onLine) {
  69080. // Adding a timestamp to by-pass browsers' cache
  69081. timeStampUsed = true;
  69082. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69083. }
  69084. xhr.open("GET", manifestURL, true);
  69085. xhr.addEventListener("load", function () {
  69086. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69087. try {
  69088. var manifestFile = JSON.parse(xhr.response);
  69089. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69090. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69091. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69092. _this.manifestVersionFound = manifestFile.version;
  69093. }
  69094. if (_this.callbackManifestChecked) {
  69095. _this.callbackManifestChecked(true);
  69096. }
  69097. }
  69098. catch (ex) {
  69099. noManifestFile();
  69100. }
  69101. }
  69102. else {
  69103. noManifestFile();
  69104. }
  69105. }, false);
  69106. xhr.addEventListener("error", function (event) {
  69107. if (timeStampUsed) {
  69108. timeStampUsed = false;
  69109. // Let's retry without the timeStamp
  69110. // It could fail when coupled with HTML5 Offline API
  69111. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69112. xhr.open("GET", retryManifestURL, true);
  69113. xhr.send();
  69114. }
  69115. else {
  69116. noManifestFile();
  69117. }
  69118. }, false);
  69119. try {
  69120. xhr.send();
  69121. }
  69122. catch (ex) {
  69123. BABYLON.Tools.Error("Error on XHR send request.");
  69124. this.callbackManifestChecked(false);
  69125. }
  69126. };
  69127. /**
  69128. * Open the database and make it available
  69129. * @param successCallback defines the callback to call on success
  69130. * @param errorCallback defines the callback to call on error
  69131. */
  69132. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69133. var _this = this;
  69134. var handleError = function () {
  69135. _this.isSupported = false;
  69136. if (errorCallback)
  69137. errorCallback();
  69138. };
  69139. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69140. // Your browser doesn't support IndexedDB
  69141. this.isSupported = false;
  69142. if (errorCallback)
  69143. errorCallback();
  69144. }
  69145. else {
  69146. // If the DB hasn't been opened or created yet
  69147. if (!this.db) {
  69148. this.hasReachedQuota = false;
  69149. this.isSupported = true;
  69150. var request = this.idbFactory.open("babylonjs", 1);
  69151. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69152. request.onerror = function (event) {
  69153. handleError();
  69154. };
  69155. // executes when a version change transaction cannot complete due to other active transactions
  69156. request.onblocked = function (event) {
  69157. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69158. handleError();
  69159. };
  69160. // DB has been opened successfully
  69161. request.onsuccess = function (event) {
  69162. _this.db = request.result;
  69163. successCallback();
  69164. };
  69165. // Initialization of the DB. Creating Scenes & Textures stores
  69166. request.onupgradeneeded = function (event) {
  69167. _this.db = (event.target).result;
  69168. if (_this.db) {
  69169. try {
  69170. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69171. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69172. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69173. }
  69174. catch (ex) {
  69175. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69176. handleError();
  69177. }
  69178. }
  69179. };
  69180. }
  69181. // DB has already been created and opened
  69182. else {
  69183. if (successCallback)
  69184. successCallback();
  69185. }
  69186. }
  69187. };
  69188. /**
  69189. * Loads an image from the database
  69190. * @param url defines the url to load from
  69191. * @param image defines the target DOM image
  69192. */
  69193. Database.prototype.loadImageFromDB = function (url, image) {
  69194. var _this = this;
  69195. var completeURL = Database._ReturnFullUrlLocation(url);
  69196. var saveAndLoadImage = function () {
  69197. if (!_this.hasReachedQuota && _this.db !== null) {
  69198. // the texture is not yet in the DB, let's try to save it
  69199. _this._saveImageIntoDBAsync(completeURL, image);
  69200. }
  69201. // If the texture is not in the DB and we've reached the DB quota limit
  69202. // let's load it directly from the web
  69203. else {
  69204. image.src = url;
  69205. }
  69206. };
  69207. if (!this.mustUpdateRessources) {
  69208. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69209. }
  69210. // First time we're download the images or update requested in the manifest file by a version change
  69211. else {
  69212. saveAndLoadImage();
  69213. }
  69214. };
  69215. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69216. if (this.isSupported && this.db !== null) {
  69217. var texture;
  69218. var transaction = this.db.transaction(["textures"]);
  69219. transaction.onabort = function (event) {
  69220. image.src = url;
  69221. };
  69222. transaction.oncomplete = function (event) {
  69223. var blobTextureURL;
  69224. if (texture) {
  69225. var URL = window.URL || window.webkitURL;
  69226. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69227. image.onerror = function () {
  69228. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69229. image.src = url;
  69230. };
  69231. image.src = blobTextureURL;
  69232. }
  69233. else {
  69234. notInDBCallback();
  69235. }
  69236. };
  69237. var getRequest = transaction.objectStore("textures").get(url);
  69238. getRequest.onsuccess = function (event) {
  69239. texture = (event.target).result;
  69240. };
  69241. getRequest.onerror = function (event) {
  69242. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69243. image.src = url;
  69244. };
  69245. }
  69246. else {
  69247. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69248. image.src = url;
  69249. }
  69250. };
  69251. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69252. var _this = this;
  69253. if (this.isSupported) {
  69254. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69255. var generateBlobUrl = function () {
  69256. var blobTextureURL;
  69257. if (blob) {
  69258. var URL = window.URL || window.webkitURL;
  69259. try {
  69260. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69261. }
  69262. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69263. catch (ex) {
  69264. blobTextureURL = URL.createObjectURL(blob);
  69265. }
  69266. }
  69267. if (blobTextureURL) {
  69268. image.src = blobTextureURL;
  69269. }
  69270. };
  69271. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69272. var xhr = new XMLHttpRequest(), blob;
  69273. xhr.open("GET", url, true);
  69274. xhr.responseType = "blob";
  69275. xhr.addEventListener("load", function () {
  69276. if (xhr.status === 200 && _this.db) {
  69277. // Blob as response (XHR2)
  69278. blob = xhr.response;
  69279. var transaction = _this.db.transaction(["textures"], "readwrite");
  69280. // the transaction could abort because of a QuotaExceededError error
  69281. transaction.onabort = function (event) {
  69282. try {
  69283. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69284. var srcElement = (event.srcElement || event.target);
  69285. var error = srcElement.error;
  69286. if (error && error.name === "QuotaExceededError") {
  69287. _this.hasReachedQuota = true;
  69288. }
  69289. }
  69290. catch (ex) { }
  69291. generateBlobUrl();
  69292. };
  69293. transaction.oncomplete = function (event) {
  69294. generateBlobUrl();
  69295. };
  69296. var newTexture = { textureUrl: url, data: blob };
  69297. try {
  69298. // Put the blob into the dabase
  69299. var addRequest = transaction.objectStore("textures").put(newTexture);
  69300. addRequest.onsuccess = function (event) {
  69301. };
  69302. addRequest.onerror = function (event) {
  69303. generateBlobUrl();
  69304. };
  69305. }
  69306. catch (ex) {
  69307. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69308. if (ex.code === 25) {
  69309. Database.IsUASupportingBlobStorage = false;
  69310. }
  69311. image.src = url;
  69312. }
  69313. }
  69314. else {
  69315. image.src = url;
  69316. }
  69317. }, false);
  69318. xhr.addEventListener("error", function (event) {
  69319. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69320. image.src = url;
  69321. }, false);
  69322. xhr.send();
  69323. }
  69324. else {
  69325. image.src = url;
  69326. }
  69327. }
  69328. else {
  69329. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69330. image.src = url;
  69331. }
  69332. };
  69333. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69334. var _this = this;
  69335. var updateVersion = function () {
  69336. // the version is not yet in the DB or we need to update it
  69337. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69338. };
  69339. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69340. };
  69341. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69342. var _this = this;
  69343. if (this.isSupported && this.db) {
  69344. var version;
  69345. try {
  69346. var transaction = this.db.transaction(["versions"]);
  69347. transaction.oncomplete = function (event) {
  69348. if (version) {
  69349. // If the version in the JSON file is different from the version in DB
  69350. if (_this.manifestVersionFound !== version.data) {
  69351. _this.mustUpdateRessources = true;
  69352. updateInDBCallback();
  69353. }
  69354. else {
  69355. callback(version.data);
  69356. }
  69357. }
  69358. // version was not found in DB
  69359. else {
  69360. _this.mustUpdateRessources = true;
  69361. updateInDBCallback();
  69362. }
  69363. };
  69364. transaction.onabort = function (event) {
  69365. callback(-1);
  69366. };
  69367. var getRequest = transaction.objectStore("versions").get(url);
  69368. getRequest.onsuccess = function (event) {
  69369. version = (event.target).result;
  69370. };
  69371. getRequest.onerror = function (event) {
  69372. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69373. callback(-1);
  69374. };
  69375. }
  69376. catch (ex) {
  69377. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69378. callback(-1);
  69379. }
  69380. }
  69381. else {
  69382. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69383. callback(-1);
  69384. }
  69385. };
  69386. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69387. var _this = this;
  69388. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69389. try {
  69390. // Open a transaction to the database
  69391. var transaction = this.db.transaction(["versions"], "readwrite");
  69392. // the transaction could abort because of a QuotaExceededError error
  69393. transaction.onabort = function (event) {
  69394. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69395. var error = event.srcElement['error'];
  69396. if (error && error.name === "QuotaExceededError") {
  69397. _this.hasReachedQuota = true;
  69398. }
  69399. }
  69400. catch (ex) { }
  69401. callback(-1);
  69402. };
  69403. transaction.oncomplete = function (event) {
  69404. callback(_this.manifestVersionFound);
  69405. };
  69406. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69407. // Put the scene into the database
  69408. var addRequest = transaction.objectStore("versions").put(newVersion);
  69409. addRequest.onsuccess = function (event) {
  69410. };
  69411. addRequest.onerror = function (event) {
  69412. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69413. };
  69414. }
  69415. catch (ex) {
  69416. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69417. callback(-1);
  69418. }
  69419. }
  69420. else {
  69421. callback(-1);
  69422. }
  69423. };
  69424. /**
  69425. * Loads a file from database
  69426. * @param url defines the URL to load from
  69427. * @param sceneLoaded defines a callback to call on success
  69428. * @param progressCallBack defines a callback to call when progress changed
  69429. * @param errorCallback defines a callback to call on error
  69430. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69431. */
  69432. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69433. var _this = this;
  69434. var completeUrl = Database._ReturnFullUrlLocation(url);
  69435. var saveAndLoadFile = function () {
  69436. // the scene is not yet in the DB, let's try to save it
  69437. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69438. };
  69439. this._checkVersionFromDB(completeUrl, function (version) {
  69440. if (version !== -1) {
  69441. if (!_this.mustUpdateRessources) {
  69442. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69443. }
  69444. else {
  69445. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69446. }
  69447. }
  69448. else {
  69449. if (errorCallback) {
  69450. errorCallback();
  69451. }
  69452. }
  69453. });
  69454. };
  69455. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69456. if (this.isSupported && this.db) {
  69457. var targetStore;
  69458. if (url.indexOf(".babylon") !== -1) {
  69459. targetStore = "scenes";
  69460. }
  69461. else {
  69462. targetStore = "textures";
  69463. }
  69464. var file;
  69465. var transaction = this.db.transaction([targetStore]);
  69466. transaction.oncomplete = function (event) {
  69467. if (file) {
  69468. callback(file.data);
  69469. }
  69470. // file was not found in DB
  69471. else {
  69472. notInDBCallback();
  69473. }
  69474. };
  69475. transaction.onabort = function (event) {
  69476. notInDBCallback();
  69477. };
  69478. var getRequest = transaction.objectStore(targetStore).get(url);
  69479. getRequest.onsuccess = function (event) {
  69480. file = (event.target).result;
  69481. };
  69482. getRequest.onerror = function (event) {
  69483. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69484. notInDBCallback();
  69485. };
  69486. }
  69487. else {
  69488. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69489. callback();
  69490. }
  69491. };
  69492. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69493. var _this = this;
  69494. if (this.isSupported) {
  69495. var targetStore;
  69496. if (url.indexOf(".babylon") !== -1) {
  69497. targetStore = "scenes";
  69498. }
  69499. else {
  69500. targetStore = "textures";
  69501. }
  69502. // Create XHR
  69503. var xhr = new XMLHttpRequest();
  69504. var fileData;
  69505. xhr.open("GET", url, true);
  69506. if (useArrayBuffer) {
  69507. xhr.responseType = "arraybuffer";
  69508. }
  69509. if (progressCallback) {
  69510. xhr.onprogress = progressCallback;
  69511. }
  69512. xhr.addEventListener("load", function () {
  69513. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69514. // Blob as response (XHR2)
  69515. //fileData = xhr.responseText;
  69516. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69517. if (!_this.hasReachedQuota && _this.db) {
  69518. // Open a transaction to the database
  69519. var transaction = _this.db.transaction([targetStore], "readwrite");
  69520. // the transaction could abort because of a QuotaExceededError error
  69521. transaction.onabort = function (event) {
  69522. try {
  69523. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69524. var error = event.srcElement['error'];
  69525. if (error && error.name === "QuotaExceededError") {
  69526. _this.hasReachedQuota = true;
  69527. }
  69528. }
  69529. catch (ex) { }
  69530. callback(fileData);
  69531. };
  69532. transaction.oncomplete = function (event) {
  69533. callback(fileData);
  69534. };
  69535. var newFile;
  69536. if (targetStore === "scenes") {
  69537. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69538. }
  69539. else {
  69540. newFile = { textureUrl: url, data: fileData };
  69541. }
  69542. try {
  69543. // Put the scene into the database
  69544. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69545. addRequest.onsuccess = function (event) {
  69546. };
  69547. addRequest.onerror = function (event) {
  69548. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69549. };
  69550. }
  69551. catch (ex) {
  69552. callback(fileData);
  69553. }
  69554. }
  69555. else {
  69556. callback(fileData);
  69557. }
  69558. }
  69559. else {
  69560. callback();
  69561. }
  69562. }, false);
  69563. xhr.addEventListener("error", function (event) {
  69564. BABYLON.Tools.Error("error on XHR request.");
  69565. callback();
  69566. }, false);
  69567. xhr.send();
  69568. }
  69569. else {
  69570. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69571. callback();
  69572. }
  69573. };
  69574. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69575. Database.IsUASupportingBlobStorage = true;
  69576. /** Gets a boolean indicating if Database storate is enabled */
  69577. Database.IDBStorageEnabled = true;
  69578. Database._ParseURL = function (url) {
  69579. var a = document.createElement('a');
  69580. a.href = url;
  69581. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69582. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69583. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69584. return absLocation;
  69585. };
  69586. Database._ReturnFullUrlLocation = function (url) {
  69587. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69588. return (Database._ParseURL(window.location.href) + url);
  69589. }
  69590. else {
  69591. return url;
  69592. }
  69593. };
  69594. return Database;
  69595. }());
  69596. BABYLON.Database = Database;
  69597. })(BABYLON || (BABYLON = {}));
  69598. //# sourceMappingURL=babylon.database.js.map
  69599. var BABYLON;
  69600. (function (BABYLON) {
  69601. var FresnelParameters = /** @class */ (function () {
  69602. function FresnelParameters() {
  69603. this._isEnabled = true;
  69604. this.leftColor = BABYLON.Color3.White();
  69605. this.rightColor = BABYLON.Color3.Black();
  69606. this.bias = 0;
  69607. this.power = 1;
  69608. }
  69609. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69610. get: function () {
  69611. return this._isEnabled;
  69612. },
  69613. set: function (value) {
  69614. if (this._isEnabled === value) {
  69615. return;
  69616. }
  69617. this._isEnabled = value;
  69618. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69619. },
  69620. enumerable: true,
  69621. configurable: true
  69622. });
  69623. FresnelParameters.prototype.clone = function () {
  69624. var newFresnelParameters = new FresnelParameters();
  69625. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69626. return newFresnelParameters;
  69627. };
  69628. FresnelParameters.prototype.serialize = function () {
  69629. var serializationObject = {};
  69630. serializationObject.isEnabled = this.isEnabled;
  69631. serializationObject.leftColor = this.leftColor.asArray();
  69632. serializationObject.rightColor = this.rightColor.asArray();
  69633. serializationObject.bias = this.bias;
  69634. serializationObject.power = this.power;
  69635. return serializationObject;
  69636. };
  69637. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69638. var fresnelParameters = new FresnelParameters();
  69639. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69640. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69641. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69642. fresnelParameters.bias = parsedFresnelParameters.bias;
  69643. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69644. return fresnelParameters;
  69645. };
  69646. return FresnelParameters;
  69647. }());
  69648. BABYLON.FresnelParameters = FresnelParameters;
  69649. })(BABYLON || (BABYLON = {}));
  69650. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69651. var BABYLON;
  69652. (function (BABYLON) {
  69653. var MultiMaterial = /** @class */ (function (_super) {
  69654. __extends(MultiMaterial, _super);
  69655. function MultiMaterial(name, scene) {
  69656. var _this = _super.call(this, name, scene, true) || this;
  69657. scene.multiMaterials.push(_this);
  69658. _this.subMaterials = new Array();
  69659. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69660. return _this;
  69661. }
  69662. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69663. get: function () {
  69664. return this._subMaterials;
  69665. },
  69666. set: function (value) {
  69667. this._subMaterials = value;
  69668. this._hookArray(value);
  69669. },
  69670. enumerable: true,
  69671. configurable: true
  69672. });
  69673. MultiMaterial.prototype._hookArray = function (array) {
  69674. var _this = this;
  69675. var oldPush = array.push;
  69676. array.push = function () {
  69677. var items = [];
  69678. for (var _i = 0; _i < arguments.length; _i++) {
  69679. items[_i] = arguments[_i];
  69680. }
  69681. var result = oldPush.apply(array, items);
  69682. _this._markAllSubMeshesAsTexturesDirty();
  69683. return result;
  69684. };
  69685. var oldSplice = array.splice;
  69686. array.splice = function (index, deleteCount) {
  69687. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69688. _this._markAllSubMeshesAsTexturesDirty();
  69689. return deleted;
  69690. };
  69691. };
  69692. // Properties
  69693. MultiMaterial.prototype.getSubMaterial = function (index) {
  69694. if (index < 0 || index >= this.subMaterials.length) {
  69695. return this.getScene().defaultMaterial;
  69696. }
  69697. return this.subMaterials[index];
  69698. };
  69699. MultiMaterial.prototype.getActiveTextures = function () {
  69700. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69701. if (subMaterial) {
  69702. return subMaterial.getActiveTextures();
  69703. }
  69704. else {
  69705. return [];
  69706. }
  69707. }));
  69708. var _a;
  69709. };
  69710. // Methods
  69711. MultiMaterial.prototype.getClassName = function () {
  69712. return "MultiMaterial";
  69713. };
  69714. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69715. for (var index = 0; index < this.subMaterials.length; index++) {
  69716. var subMaterial = this.subMaterials[index];
  69717. if (subMaterial) {
  69718. if (subMaterial.storeEffectOnSubMeshes) {
  69719. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69720. return false;
  69721. }
  69722. continue;
  69723. }
  69724. if (!subMaterial.isReady(mesh)) {
  69725. return false;
  69726. }
  69727. }
  69728. }
  69729. return true;
  69730. };
  69731. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69732. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69733. for (var index = 0; index < this.subMaterials.length; index++) {
  69734. var subMaterial = null;
  69735. var current = this.subMaterials[index];
  69736. if (cloneChildren && current) {
  69737. subMaterial = current.clone(name + "-" + current.name);
  69738. }
  69739. else {
  69740. subMaterial = this.subMaterials[index];
  69741. }
  69742. newMultiMaterial.subMaterials.push(subMaterial);
  69743. }
  69744. return newMultiMaterial;
  69745. };
  69746. MultiMaterial.prototype.serialize = function () {
  69747. var serializationObject = {};
  69748. serializationObject.name = this.name;
  69749. serializationObject.id = this.id;
  69750. if (BABYLON.Tags) {
  69751. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69752. }
  69753. serializationObject.materials = [];
  69754. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69755. var subMat = this.subMaterials[matIndex];
  69756. if (subMat) {
  69757. serializationObject.materials.push(subMat.id);
  69758. }
  69759. else {
  69760. serializationObject.materials.push(null);
  69761. }
  69762. }
  69763. return serializationObject;
  69764. };
  69765. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69766. var scene = this.getScene();
  69767. if (!scene) {
  69768. return;
  69769. }
  69770. var index = scene.multiMaterials.indexOf(this);
  69771. if (index >= 0) {
  69772. scene.multiMaterials.splice(index, 1);
  69773. }
  69774. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69775. };
  69776. return MultiMaterial;
  69777. }(BABYLON.Material));
  69778. BABYLON.MultiMaterial = MultiMaterial;
  69779. })(BABYLON || (BABYLON = {}));
  69780. //# sourceMappingURL=babylon.multiMaterial.js.map
  69781. var BABYLON;
  69782. (function (BABYLON) {
  69783. var FreeCameraTouchInput = /** @class */ (function () {
  69784. function FreeCameraTouchInput() {
  69785. this._offsetX = null;
  69786. this._offsetY = null;
  69787. this._pointerPressed = new Array();
  69788. this.touchAngularSensibility = 200000.0;
  69789. this.touchMoveSensibility = 250.0;
  69790. }
  69791. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69792. var _this = this;
  69793. var previousPosition = null;
  69794. if (this._pointerInput === undefined) {
  69795. this._onLostFocus = function (evt) {
  69796. _this._offsetX = null;
  69797. _this._offsetY = null;
  69798. };
  69799. this._pointerInput = function (p, s) {
  69800. var evt = p.event;
  69801. if (evt.pointerType === "mouse") {
  69802. return;
  69803. }
  69804. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69805. if (!noPreventDefault) {
  69806. evt.preventDefault();
  69807. }
  69808. _this._pointerPressed.push(evt.pointerId);
  69809. if (_this._pointerPressed.length !== 1) {
  69810. return;
  69811. }
  69812. previousPosition = {
  69813. x: evt.clientX,
  69814. y: evt.clientY
  69815. };
  69816. }
  69817. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69818. if (!noPreventDefault) {
  69819. evt.preventDefault();
  69820. }
  69821. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69822. if (index === -1) {
  69823. return;
  69824. }
  69825. _this._pointerPressed.splice(index, 1);
  69826. if (index != 0) {
  69827. return;
  69828. }
  69829. previousPosition = null;
  69830. _this._offsetX = null;
  69831. _this._offsetY = null;
  69832. }
  69833. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69834. if (!noPreventDefault) {
  69835. evt.preventDefault();
  69836. }
  69837. if (!previousPosition) {
  69838. return;
  69839. }
  69840. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69841. if (index != 0) {
  69842. return;
  69843. }
  69844. _this._offsetX = evt.clientX - previousPosition.x;
  69845. _this._offsetY = -(evt.clientY - previousPosition.y);
  69846. }
  69847. };
  69848. }
  69849. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69850. if (this._onLostFocus) {
  69851. element.addEventListener("blur", this._onLostFocus);
  69852. }
  69853. };
  69854. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69855. if (this._pointerInput && element) {
  69856. if (this._observer) {
  69857. this.camera.getScene().onPointerObservable.remove(this._observer);
  69858. this._observer = null;
  69859. }
  69860. if (this._onLostFocus) {
  69861. element.removeEventListener("blur", this._onLostFocus);
  69862. this._onLostFocus = null;
  69863. }
  69864. this._pointerPressed = [];
  69865. this._offsetX = null;
  69866. this._offsetY = null;
  69867. }
  69868. };
  69869. FreeCameraTouchInput.prototype.checkInputs = function () {
  69870. if (this._offsetX && this._offsetY) {
  69871. var camera = this.camera;
  69872. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69873. if (this._pointerPressed.length > 1) {
  69874. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69875. }
  69876. else {
  69877. var speed = camera._computeLocalCameraSpeed();
  69878. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69879. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69880. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69881. }
  69882. }
  69883. };
  69884. FreeCameraTouchInput.prototype.getClassName = function () {
  69885. return "FreeCameraTouchInput";
  69886. };
  69887. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69888. return "touch";
  69889. };
  69890. __decorate([
  69891. BABYLON.serialize()
  69892. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69893. __decorate([
  69894. BABYLON.serialize()
  69895. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69896. return FreeCameraTouchInput;
  69897. }());
  69898. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69899. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69900. })(BABYLON || (BABYLON = {}));
  69901. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69902. var BABYLON;
  69903. (function (BABYLON) {
  69904. // We're mainly based on the logic defined into the FreeCamera code
  69905. var TouchCamera = /** @class */ (function (_super) {
  69906. __extends(TouchCamera, _super);
  69907. //-- end properties for backward compatibility for inputs
  69908. function TouchCamera(name, position, scene) {
  69909. var _this = _super.call(this, name, position, scene) || this;
  69910. _this.inputs.addTouch();
  69911. _this._setupInputs();
  69912. return _this;
  69913. }
  69914. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69915. //-- Begin properties for backward compatibility for inputs
  69916. get: function () {
  69917. var touch = this.inputs.attached["touch"];
  69918. if (touch)
  69919. return touch.touchAngularSensibility;
  69920. return 0;
  69921. },
  69922. set: function (value) {
  69923. var touch = this.inputs.attached["touch"];
  69924. if (touch)
  69925. touch.touchAngularSensibility = value;
  69926. },
  69927. enumerable: true,
  69928. configurable: true
  69929. });
  69930. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69931. get: function () {
  69932. var touch = this.inputs.attached["touch"];
  69933. if (touch)
  69934. return touch.touchMoveSensibility;
  69935. return 0;
  69936. },
  69937. set: function (value) {
  69938. var touch = this.inputs.attached["touch"];
  69939. if (touch)
  69940. touch.touchMoveSensibility = value;
  69941. },
  69942. enumerable: true,
  69943. configurable: true
  69944. });
  69945. TouchCamera.prototype.getClassName = function () {
  69946. return "TouchCamera";
  69947. };
  69948. TouchCamera.prototype._setupInputs = function () {
  69949. var mouse = this.inputs.attached["mouse"];
  69950. if (mouse) {
  69951. mouse.touchEnabled = false;
  69952. }
  69953. };
  69954. return TouchCamera;
  69955. }(BABYLON.FreeCamera));
  69956. BABYLON.TouchCamera = TouchCamera;
  69957. })(BABYLON || (BABYLON = {}));
  69958. //# sourceMappingURL=babylon.touchCamera.js.map
  69959. var BABYLON;
  69960. (function (BABYLON) {
  69961. var ProceduralTexture = /** @class */ (function (_super) {
  69962. __extends(ProceduralTexture, _super);
  69963. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69964. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69965. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69966. if (isCube === void 0) { isCube = false; }
  69967. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69968. _this.isCube = isCube;
  69969. _this.isEnabled = true;
  69970. _this._currentRefreshId = -1;
  69971. _this._refreshRate = 1;
  69972. _this._vertexBuffers = {};
  69973. _this._uniforms = new Array();
  69974. _this._samplers = new Array();
  69975. _this._textures = {};
  69976. _this._floats = {};
  69977. _this._floatsArrays = {};
  69978. _this._colors3 = {};
  69979. _this._colors4 = {};
  69980. _this._vectors2 = {};
  69981. _this._vectors3 = {};
  69982. _this._matrices = {};
  69983. _this._fallbackTextureUsed = false;
  69984. scene.proceduralTextures.push(_this);
  69985. _this._engine = scene.getEngine();
  69986. _this.name = name;
  69987. _this.isRenderTarget = true;
  69988. _this._size = size;
  69989. _this._generateMipMaps = generateMipMaps;
  69990. _this.setFragment(fragment);
  69991. _this._fallbackTexture = fallbackTexture;
  69992. if (isCube) {
  69993. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69994. _this.setFloat("face", 0);
  69995. }
  69996. else {
  69997. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69998. }
  69999. // VBO
  70000. var vertices = [];
  70001. vertices.push(1, 1);
  70002. vertices.push(-1, 1);
  70003. vertices.push(-1, -1);
  70004. vertices.push(1, -1);
  70005. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70006. _this._createIndexBuffer();
  70007. return _this;
  70008. }
  70009. ProceduralTexture.prototype._createIndexBuffer = function () {
  70010. var engine = this._engine;
  70011. // Indices
  70012. var indices = [];
  70013. indices.push(0);
  70014. indices.push(1);
  70015. indices.push(2);
  70016. indices.push(0);
  70017. indices.push(2);
  70018. indices.push(3);
  70019. this._indexBuffer = engine.createIndexBuffer(indices);
  70020. };
  70021. ProceduralTexture.prototype._rebuild = function () {
  70022. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70023. if (vb) {
  70024. vb._rebuild();
  70025. }
  70026. this._createIndexBuffer();
  70027. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70028. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70029. }
  70030. };
  70031. ProceduralTexture.prototype.reset = function () {
  70032. if (this._effect === undefined) {
  70033. return;
  70034. }
  70035. var engine = this._engine;
  70036. engine._releaseEffect(this._effect);
  70037. };
  70038. ProceduralTexture.prototype.isReady = function () {
  70039. var _this = this;
  70040. var engine = this._engine;
  70041. var shaders;
  70042. if (!this._fragment) {
  70043. return false;
  70044. }
  70045. if (this._fallbackTextureUsed) {
  70046. return true;
  70047. }
  70048. if (this._fragment.fragmentElement !== undefined) {
  70049. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70050. }
  70051. else {
  70052. shaders = { vertex: "procedural", fragment: this._fragment };
  70053. }
  70054. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70055. _this.releaseInternalTexture();
  70056. if (_this._fallbackTexture) {
  70057. _this._texture = _this._fallbackTexture._texture;
  70058. if (_this._texture) {
  70059. _this._texture.incrementReferences();
  70060. }
  70061. }
  70062. _this._fallbackTextureUsed = true;
  70063. });
  70064. return this._effect.isReady();
  70065. };
  70066. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70067. this._currentRefreshId = -1;
  70068. };
  70069. ProceduralTexture.prototype.setFragment = function (fragment) {
  70070. this._fragment = fragment;
  70071. };
  70072. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70073. get: function () {
  70074. return this._refreshRate;
  70075. },
  70076. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70077. set: function (value) {
  70078. this._refreshRate = value;
  70079. this.resetRefreshCounter();
  70080. },
  70081. enumerable: true,
  70082. configurable: true
  70083. });
  70084. ProceduralTexture.prototype._shouldRender = function () {
  70085. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70086. return false;
  70087. }
  70088. if (this._fallbackTextureUsed) {
  70089. return false;
  70090. }
  70091. if (this._currentRefreshId === -1) { // At least render once
  70092. this._currentRefreshId = 1;
  70093. return true;
  70094. }
  70095. if (this.refreshRate === this._currentRefreshId) {
  70096. this._currentRefreshId = 1;
  70097. return true;
  70098. }
  70099. this._currentRefreshId++;
  70100. return false;
  70101. };
  70102. ProceduralTexture.prototype.getRenderSize = function () {
  70103. return this._size;
  70104. };
  70105. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70106. if (this._fallbackTextureUsed) {
  70107. return;
  70108. }
  70109. this.releaseInternalTexture();
  70110. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70111. // Update properties
  70112. this._size = size;
  70113. this._generateMipMaps = generateMipMaps;
  70114. };
  70115. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70116. if (this._uniforms.indexOf(uniformName) === -1) {
  70117. this._uniforms.push(uniformName);
  70118. }
  70119. };
  70120. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70121. if (this._samplers.indexOf(name) === -1) {
  70122. this._samplers.push(name);
  70123. }
  70124. this._textures[name] = texture;
  70125. return this;
  70126. };
  70127. ProceduralTexture.prototype.setFloat = function (name, value) {
  70128. this._checkUniform(name);
  70129. this._floats[name] = value;
  70130. return this;
  70131. };
  70132. ProceduralTexture.prototype.setFloats = function (name, value) {
  70133. this._checkUniform(name);
  70134. this._floatsArrays[name] = value;
  70135. return this;
  70136. };
  70137. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70138. this._checkUniform(name);
  70139. this._colors3[name] = value;
  70140. return this;
  70141. };
  70142. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70143. this._checkUniform(name);
  70144. this._colors4[name] = value;
  70145. return this;
  70146. };
  70147. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70148. this._checkUniform(name);
  70149. this._vectors2[name] = value;
  70150. return this;
  70151. };
  70152. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70153. this._checkUniform(name);
  70154. this._vectors3[name] = value;
  70155. return this;
  70156. };
  70157. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70158. this._checkUniform(name);
  70159. this._matrices[name] = value;
  70160. return this;
  70161. };
  70162. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70163. var scene = this.getScene();
  70164. if (!scene) {
  70165. return;
  70166. }
  70167. var engine = this._engine;
  70168. // Render
  70169. engine.enableEffect(this._effect);
  70170. engine.setState(false);
  70171. // Texture
  70172. for (var name in this._textures) {
  70173. this._effect.setTexture(name, this._textures[name]);
  70174. }
  70175. // Float
  70176. for (name in this._floats) {
  70177. this._effect.setFloat(name, this._floats[name]);
  70178. }
  70179. // Floats
  70180. for (name in this._floatsArrays) {
  70181. this._effect.setArray(name, this._floatsArrays[name]);
  70182. }
  70183. // Color3
  70184. for (name in this._colors3) {
  70185. this._effect.setColor3(name, this._colors3[name]);
  70186. }
  70187. // Color4
  70188. for (name in this._colors4) {
  70189. var color = this._colors4[name];
  70190. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70191. }
  70192. // Vector2
  70193. for (name in this._vectors2) {
  70194. this._effect.setVector2(name, this._vectors2[name]);
  70195. }
  70196. // Vector3
  70197. for (name in this._vectors3) {
  70198. this._effect.setVector3(name, this._vectors3[name]);
  70199. }
  70200. // Matrix
  70201. for (name in this._matrices) {
  70202. this._effect.setMatrix(name, this._matrices[name]);
  70203. }
  70204. if (!this._texture) {
  70205. return;
  70206. }
  70207. if (this.isCube) {
  70208. for (var face = 0; face < 6; face++) {
  70209. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70210. // VBOs
  70211. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70212. this._effect.setFloat("face", face);
  70213. // Clear
  70214. engine.clear(scene.clearColor, true, true, true);
  70215. // Draw order
  70216. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70217. // Mipmaps
  70218. if (face === 5) {
  70219. engine.generateMipMapsForCubemap(this._texture);
  70220. }
  70221. }
  70222. }
  70223. else {
  70224. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70225. // VBOs
  70226. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70227. // Clear
  70228. engine.clear(scene.clearColor, true, true, true);
  70229. // Draw order
  70230. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70231. }
  70232. // Unbind
  70233. engine.unBindFramebuffer(this._texture, this.isCube);
  70234. if (this.onGenerated) {
  70235. this.onGenerated();
  70236. }
  70237. };
  70238. ProceduralTexture.prototype.clone = function () {
  70239. var textureSize = this.getSize();
  70240. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70241. // Base texture
  70242. newTexture.hasAlpha = this.hasAlpha;
  70243. newTexture.level = this.level;
  70244. // RenderTarget Texture
  70245. newTexture.coordinatesMode = this.coordinatesMode;
  70246. return newTexture;
  70247. };
  70248. ProceduralTexture.prototype.dispose = function () {
  70249. var scene = this.getScene();
  70250. if (!scene) {
  70251. return;
  70252. }
  70253. var index = scene.proceduralTextures.indexOf(this);
  70254. if (index >= 0) {
  70255. scene.proceduralTextures.splice(index, 1);
  70256. }
  70257. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70258. if (vertexBuffer) {
  70259. vertexBuffer.dispose();
  70260. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70261. }
  70262. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70263. this._indexBuffer = null;
  70264. }
  70265. _super.prototype.dispose.call(this);
  70266. };
  70267. __decorate([
  70268. BABYLON.serialize()
  70269. ], ProceduralTexture.prototype, "_size", void 0);
  70270. __decorate([
  70271. BABYLON.serialize()
  70272. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70273. __decorate([
  70274. BABYLON.serialize()
  70275. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70276. __decorate([
  70277. BABYLON.serialize()
  70278. ], ProceduralTexture.prototype, "refreshRate", null);
  70279. return ProceduralTexture;
  70280. }(BABYLON.Texture));
  70281. BABYLON.ProceduralTexture = ProceduralTexture;
  70282. })(BABYLON || (BABYLON = {}));
  70283. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70284. var BABYLON;
  70285. (function (BABYLON) {
  70286. var CustomProceduralTexture = /** @class */ (function (_super) {
  70287. __extends(CustomProceduralTexture, _super);
  70288. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70289. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70290. _this._animate = true;
  70291. _this._time = 0;
  70292. _this._texturePath = texturePath;
  70293. //Try to load json
  70294. _this.loadJson(texturePath);
  70295. _this.refreshRate = 1;
  70296. return _this;
  70297. }
  70298. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70299. var _this = this;
  70300. var noConfigFile = function () {
  70301. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70302. try {
  70303. _this.setFragment(_this._texturePath);
  70304. }
  70305. catch (ex) {
  70306. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70307. }
  70308. };
  70309. var configFileUrl = jsonUrl + "/config.json";
  70310. var xhr = new XMLHttpRequest();
  70311. xhr.open("GET", configFileUrl, true);
  70312. xhr.addEventListener("load", function () {
  70313. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70314. try {
  70315. _this._config = JSON.parse(xhr.response);
  70316. _this.updateShaderUniforms();
  70317. _this.updateTextures();
  70318. _this.setFragment(_this._texturePath + "/custom");
  70319. _this._animate = _this._config.animate;
  70320. _this.refreshRate = _this._config.refreshrate;
  70321. }
  70322. catch (ex) {
  70323. noConfigFile();
  70324. }
  70325. }
  70326. else {
  70327. noConfigFile();
  70328. }
  70329. }, false);
  70330. xhr.addEventListener("error", function () {
  70331. noConfigFile();
  70332. }, false);
  70333. try {
  70334. xhr.send();
  70335. }
  70336. catch (ex) {
  70337. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70338. }
  70339. };
  70340. CustomProceduralTexture.prototype.isReady = function () {
  70341. if (!_super.prototype.isReady.call(this)) {
  70342. return false;
  70343. }
  70344. for (var name in this._textures) {
  70345. var texture = this._textures[name];
  70346. if (!texture.isReady()) {
  70347. return false;
  70348. }
  70349. }
  70350. return true;
  70351. };
  70352. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70353. var scene = this.getScene();
  70354. if (this._animate && scene) {
  70355. this._time += scene.getAnimationRatio() * 0.03;
  70356. this.updateShaderUniforms();
  70357. }
  70358. _super.prototype.render.call(this, useCameraPostProcess);
  70359. };
  70360. CustomProceduralTexture.prototype.updateTextures = function () {
  70361. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70362. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70363. }
  70364. };
  70365. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70366. if (this._config) {
  70367. for (var j = 0; j < this._config.uniforms.length; j++) {
  70368. var uniform = this._config.uniforms[j];
  70369. switch (uniform.type) {
  70370. case "float":
  70371. this.setFloat(uniform.name, uniform.value);
  70372. break;
  70373. case "color3":
  70374. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70375. break;
  70376. case "color4":
  70377. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70378. break;
  70379. case "vector2":
  70380. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70381. break;
  70382. case "vector3":
  70383. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70384. break;
  70385. }
  70386. }
  70387. }
  70388. this.setFloat("time", this._time);
  70389. };
  70390. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70391. get: function () {
  70392. return this._animate;
  70393. },
  70394. set: function (value) {
  70395. this._animate = value;
  70396. },
  70397. enumerable: true,
  70398. configurable: true
  70399. });
  70400. return CustomProceduralTexture;
  70401. }(BABYLON.ProceduralTexture));
  70402. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70403. })(BABYLON || (BABYLON = {}));
  70404. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70405. var BABYLON;
  70406. (function (BABYLON) {
  70407. var FreeCameraGamepadInput = /** @class */ (function () {
  70408. function FreeCameraGamepadInput() {
  70409. this.gamepadAngularSensibility = 200;
  70410. this.gamepadMoveSensibility = 40;
  70411. // private members
  70412. this._cameraTransform = BABYLON.Matrix.Identity();
  70413. this._deltaTransform = BABYLON.Vector3.Zero();
  70414. this._vector3 = BABYLON.Vector3.Zero();
  70415. this._vector2 = BABYLON.Vector2.Zero();
  70416. }
  70417. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70418. var _this = this;
  70419. var manager = this.camera.getScene().gamepadManager;
  70420. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70421. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70422. // prioritize XBOX gamepads.
  70423. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70424. _this.gamepad = gamepad;
  70425. }
  70426. }
  70427. });
  70428. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70429. if (_this.gamepad === gamepad) {
  70430. _this.gamepad = null;
  70431. }
  70432. });
  70433. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70434. };
  70435. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70436. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70437. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70438. this.gamepad = null;
  70439. };
  70440. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70441. if (this.gamepad && this.gamepad.leftStick) {
  70442. var camera = this.camera;
  70443. var LSValues = this.gamepad.leftStick;
  70444. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70445. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70446. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70447. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70448. var RSValues = this.gamepad.rightStick;
  70449. if (RSValues) {
  70450. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70451. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70452. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70453. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70454. }
  70455. else {
  70456. RSValues = { x: 0, y: 0 };
  70457. }
  70458. if (!camera.rotationQuaternion) {
  70459. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70460. }
  70461. else {
  70462. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70463. }
  70464. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70465. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70466. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70467. camera.cameraDirection.addInPlace(this._deltaTransform);
  70468. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70469. camera.cameraRotation.addInPlace(this._vector2);
  70470. }
  70471. };
  70472. FreeCameraGamepadInput.prototype.getClassName = function () {
  70473. return "FreeCameraGamepadInput";
  70474. };
  70475. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70476. return "gamepad";
  70477. };
  70478. __decorate([
  70479. BABYLON.serialize()
  70480. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70481. __decorate([
  70482. BABYLON.serialize()
  70483. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70484. return FreeCameraGamepadInput;
  70485. }());
  70486. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70487. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70488. })(BABYLON || (BABYLON = {}));
  70489. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70490. var BABYLON;
  70491. (function (BABYLON) {
  70492. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70493. function ArcRotateCameraGamepadInput() {
  70494. this.gamepadRotationSensibility = 80;
  70495. this.gamepadMoveSensibility = 40;
  70496. }
  70497. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70498. var _this = this;
  70499. var manager = this.camera.getScene().gamepadManager;
  70500. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70501. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70502. // prioritize XBOX gamepads.
  70503. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70504. _this.gamepad = gamepad;
  70505. }
  70506. }
  70507. });
  70508. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70509. if (_this.gamepad === gamepad) {
  70510. _this.gamepad = null;
  70511. }
  70512. });
  70513. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70514. };
  70515. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70516. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70517. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70518. this.gamepad = null;
  70519. };
  70520. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70521. if (this.gamepad) {
  70522. var camera = this.camera;
  70523. var RSValues = this.gamepad.rightStick;
  70524. if (RSValues) {
  70525. if (RSValues.x != 0) {
  70526. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70527. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70528. camera.inertialAlphaOffset += normalizedRX;
  70529. }
  70530. }
  70531. if (RSValues.y != 0) {
  70532. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70533. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70534. camera.inertialBetaOffset += normalizedRY;
  70535. }
  70536. }
  70537. }
  70538. var LSValues = this.gamepad.leftStick;
  70539. if (LSValues && LSValues.y != 0) {
  70540. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70541. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70542. this.camera.inertialRadiusOffset -= normalizedLY;
  70543. }
  70544. }
  70545. }
  70546. };
  70547. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70548. return "ArcRotateCameraGamepadInput";
  70549. };
  70550. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70551. return "gamepad";
  70552. };
  70553. __decorate([
  70554. BABYLON.serialize()
  70555. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70556. __decorate([
  70557. BABYLON.serialize()
  70558. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70559. return ArcRotateCameraGamepadInput;
  70560. }());
  70561. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70562. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70563. })(BABYLON || (BABYLON = {}));
  70564. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70565. var BABYLON;
  70566. (function (BABYLON) {
  70567. var GamepadManager = /** @class */ (function () {
  70568. function GamepadManager(_scene) {
  70569. var _this = this;
  70570. this._scene = _scene;
  70571. this._babylonGamepads = [];
  70572. this._oneGamepadConnected = false;
  70573. this._isMonitoring = false;
  70574. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70575. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70576. this._gamepadEventSupported = false;
  70577. }
  70578. else {
  70579. this._gamepadEventSupported = 'GamepadEvent' in window;
  70580. this._gamepadSupport = (navigator.getGamepads ||
  70581. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70582. }
  70583. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70584. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70585. for (var i in _this._babylonGamepads) {
  70586. var gamepad = _this._babylonGamepads[i];
  70587. if (gamepad && gamepad._isConnected) {
  70588. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70589. }
  70590. }
  70591. });
  70592. this._onGamepadConnectedEvent = function (evt) {
  70593. var gamepad = evt.gamepad;
  70594. if (gamepad.index in _this._babylonGamepads) {
  70595. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70596. return;
  70597. }
  70598. }
  70599. var newGamepad;
  70600. if (_this._babylonGamepads[gamepad.index]) {
  70601. newGamepad = _this._babylonGamepads[gamepad.index];
  70602. newGamepad.browserGamepad = gamepad;
  70603. newGamepad._isConnected = true;
  70604. }
  70605. else {
  70606. newGamepad = _this._addNewGamepad(gamepad);
  70607. }
  70608. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70609. _this._startMonitoringGamepads();
  70610. };
  70611. this._onGamepadDisconnectedEvent = function (evt) {
  70612. var gamepad = evt.gamepad;
  70613. // Remove the gamepad from the list of gamepads to monitor.
  70614. for (var i in _this._babylonGamepads) {
  70615. if (_this._babylonGamepads[i].index === gamepad.index) {
  70616. var disconnectedGamepad = _this._babylonGamepads[i];
  70617. disconnectedGamepad._isConnected = false;
  70618. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70619. break;
  70620. }
  70621. }
  70622. };
  70623. if (this._gamepadSupport) {
  70624. //first add already-connected gamepads
  70625. this._updateGamepadObjects();
  70626. if (this._babylonGamepads.length) {
  70627. this._startMonitoringGamepads();
  70628. }
  70629. // Checking if the gamepad connected event is supported (like in Firefox)
  70630. if (this._gamepadEventSupported) {
  70631. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70632. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70633. }
  70634. else {
  70635. this._startMonitoringGamepads();
  70636. }
  70637. }
  70638. }
  70639. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70640. get: function () {
  70641. return this._babylonGamepads;
  70642. },
  70643. enumerable: true,
  70644. configurable: true
  70645. });
  70646. GamepadManager.prototype.getGamepadByType = function (type) {
  70647. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70648. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70649. var gamepad = _a[_i];
  70650. if (gamepad && gamepad.type === type) {
  70651. return gamepad;
  70652. }
  70653. }
  70654. return null;
  70655. };
  70656. GamepadManager.prototype.dispose = function () {
  70657. if (this._gamepadEventSupported) {
  70658. if (this._onGamepadConnectedEvent) {
  70659. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70660. }
  70661. if (this._onGamepadDisconnectedEvent) {
  70662. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70663. }
  70664. this._onGamepadConnectedEvent = null;
  70665. this._onGamepadDisconnectedEvent = null;
  70666. }
  70667. this._babylonGamepads.forEach(function (gamepad) {
  70668. gamepad.dispose();
  70669. });
  70670. this.onGamepadConnectedObservable.clear();
  70671. this.onGamepadDisconnectedObservable.clear();
  70672. this._oneGamepadConnected = false;
  70673. this._stopMonitoringGamepads();
  70674. this._babylonGamepads = [];
  70675. };
  70676. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70677. if (!this._oneGamepadConnected) {
  70678. this._oneGamepadConnected = true;
  70679. }
  70680. var newGamepad;
  70681. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70682. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70683. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70684. }
  70685. // if pose is supported, use the (WebVR) pose enabled controller
  70686. else if (gamepad.pose) {
  70687. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70688. }
  70689. else {
  70690. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70691. }
  70692. this._babylonGamepads[newGamepad.index] = newGamepad;
  70693. return newGamepad;
  70694. };
  70695. GamepadManager.prototype._startMonitoringGamepads = function () {
  70696. if (!this._isMonitoring) {
  70697. this._isMonitoring = true;
  70698. //back-comp
  70699. if (!this._scene) {
  70700. this._checkGamepadsStatus();
  70701. }
  70702. }
  70703. };
  70704. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70705. this._isMonitoring = false;
  70706. };
  70707. GamepadManager.prototype._checkGamepadsStatus = function () {
  70708. var _this = this;
  70709. // Hack to be compatible Chrome
  70710. this._updateGamepadObjects();
  70711. for (var i in this._babylonGamepads) {
  70712. var gamepad = this._babylonGamepads[i];
  70713. if (!gamepad || !gamepad.isConnected) {
  70714. continue;
  70715. }
  70716. gamepad.update();
  70717. }
  70718. if (this._isMonitoring && !this._scene) {
  70719. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70720. }
  70721. };
  70722. // This function is called only on Chrome, which does not properly support
  70723. // connection/disconnection events and forces you to recopy again the gamepad object
  70724. GamepadManager.prototype._updateGamepadObjects = function () {
  70725. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70726. for (var i = 0; i < gamepads.length; i++) {
  70727. var gamepad = gamepads[i];
  70728. if (gamepad) {
  70729. if (!this._babylonGamepads[gamepad.index]) {
  70730. var newGamepad = this._addNewGamepad(gamepad);
  70731. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70732. }
  70733. else {
  70734. // Forced to copy again this object for Chrome for unknown reason
  70735. this._babylonGamepads[i].browserGamepad = gamepad;
  70736. if (!this._babylonGamepads[i].isConnected) {
  70737. this._babylonGamepads[i]._isConnected = true;
  70738. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70739. }
  70740. }
  70741. }
  70742. }
  70743. };
  70744. return GamepadManager;
  70745. }());
  70746. BABYLON.GamepadManager = GamepadManager;
  70747. })(BABYLON || (BABYLON = {}));
  70748. //# sourceMappingURL=babylon.gamepadManager.js.map
  70749. var BABYLON;
  70750. (function (BABYLON) {
  70751. var StickValues = /** @class */ (function () {
  70752. function StickValues(x, y) {
  70753. this.x = x;
  70754. this.y = y;
  70755. }
  70756. return StickValues;
  70757. }());
  70758. BABYLON.StickValues = StickValues;
  70759. var Gamepad = /** @class */ (function () {
  70760. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70761. if (leftStickX === void 0) { leftStickX = 0; }
  70762. if (leftStickY === void 0) { leftStickY = 1; }
  70763. if (rightStickX === void 0) { rightStickX = 2; }
  70764. if (rightStickY === void 0) { rightStickY = 3; }
  70765. this.id = id;
  70766. this.index = index;
  70767. this.browserGamepad = browserGamepad;
  70768. this._isConnected = true;
  70769. this._invertLeftStickY = false;
  70770. this.type = Gamepad.GAMEPAD;
  70771. this._leftStickAxisX = leftStickX;
  70772. this._leftStickAxisY = leftStickY;
  70773. this._rightStickAxisX = rightStickX;
  70774. this._rightStickAxisY = rightStickY;
  70775. if (this.browserGamepad.axes.length >= 2) {
  70776. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70777. }
  70778. if (this.browserGamepad.axes.length >= 4) {
  70779. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70780. }
  70781. }
  70782. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70783. get: function () {
  70784. return this._isConnected;
  70785. },
  70786. enumerable: true,
  70787. configurable: true
  70788. });
  70789. Gamepad.prototype.onleftstickchanged = function (callback) {
  70790. this._onleftstickchanged = callback;
  70791. };
  70792. Gamepad.prototype.onrightstickchanged = function (callback) {
  70793. this._onrightstickchanged = callback;
  70794. };
  70795. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70796. get: function () {
  70797. return this._leftStick;
  70798. },
  70799. set: function (newValues) {
  70800. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70801. this._onleftstickchanged(newValues);
  70802. }
  70803. this._leftStick = newValues;
  70804. },
  70805. enumerable: true,
  70806. configurable: true
  70807. });
  70808. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70809. get: function () {
  70810. return this._rightStick;
  70811. },
  70812. set: function (newValues) {
  70813. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70814. this._onrightstickchanged(newValues);
  70815. }
  70816. this._rightStick = newValues;
  70817. },
  70818. enumerable: true,
  70819. configurable: true
  70820. });
  70821. Gamepad.prototype.update = function () {
  70822. if (this._leftStick) {
  70823. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70824. if (this._invertLeftStickY) {
  70825. this.leftStick.y *= -1;
  70826. }
  70827. }
  70828. if (this._rightStick) {
  70829. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70830. }
  70831. };
  70832. Gamepad.prototype.dispose = function () {
  70833. };
  70834. Gamepad.GAMEPAD = 0;
  70835. Gamepad.GENERIC = 1;
  70836. Gamepad.XBOX = 2;
  70837. Gamepad.POSE_ENABLED = 3;
  70838. return Gamepad;
  70839. }());
  70840. BABYLON.Gamepad = Gamepad;
  70841. var GenericPad = /** @class */ (function (_super) {
  70842. __extends(GenericPad, _super);
  70843. function GenericPad(id, index, browserGamepad) {
  70844. var _this = _super.call(this, id, index, browserGamepad) || this;
  70845. _this.onButtonDownObservable = new BABYLON.Observable();
  70846. _this.onButtonUpObservable = new BABYLON.Observable();
  70847. _this.type = Gamepad.GENERIC;
  70848. _this._buttons = new Array(browserGamepad.buttons.length);
  70849. return _this;
  70850. }
  70851. GenericPad.prototype.onbuttondown = function (callback) {
  70852. this._onbuttondown = callback;
  70853. };
  70854. GenericPad.prototype.onbuttonup = function (callback) {
  70855. this._onbuttonup = callback;
  70856. };
  70857. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70858. if (newValue !== currentValue) {
  70859. if (newValue === 1) {
  70860. if (this._onbuttondown) {
  70861. this._onbuttondown(buttonIndex);
  70862. }
  70863. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70864. }
  70865. if (newValue === 0) {
  70866. if (this._onbuttonup) {
  70867. this._onbuttonup(buttonIndex);
  70868. }
  70869. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70870. }
  70871. }
  70872. return newValue;
  70873. };
  70874. GenericPad.prototype.update = function () {
  70875. _super.prototype.update.call(this);
  70876. for (var index = 0; index < this._buttons.length; index++) {
  70877. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70878. }
  70879. };
  70880. GenericPad.prototype.dispose = function () {
  70881. _super.prototype.dispose.call(this);
  70882. this.onButtonDownObservable.clear();
  70883. this.onButtonUpObservable.clear();
  70884. };
  70885. return GenericPad;
  70886. }(Gamepad));
  70887. BABYLON.GenericPad = GenericPad;
  70888. })(BABYLON || (BABYLON = {}));
  70889. //# sourceMappingURL=babylon.gamepad.js.map
  70890. var BABYLON;
  70891. (function (BABYLON) {
  70892. /**
  70893. * Defines supported buttons for XBox360 compatible gamepads
  70894. */
  70895. var Xbox360Button;
  70896. (function (Xbox360Button) {
  70897. /** A */
  70898. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70899. /** B */
  70900. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70901. /** X */
  70902. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70903. /** Y */
  70904. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70905. /** Start */
  70906. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70907. /** Back */
  70908. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70909. /** Left button */
  70910. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70911. /** Right button */
  70912. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70913. /** Left stick */
  70914. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70915. /** Right stick */
  70916. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70917. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70918. /** Defines values for XBox360 DPad */
  70919. var Xbox360Dpad;
  70920. (function (Xbox360Dpad) {
  70921. /** Up */
  70922. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70923. /** Down */
  70924. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70925. /** Left */
  70926. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70927. /** Right */
  70928. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70929. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70930. /**
  70931. * Defines a XBox360 gamepad
  70932. */
  70933. var Xbox360Pad = /** @class */ (function (_super) {
  70934. __extends(Xbox360Pad, _super);
  70935. /**
  70936. * Creates a new XBox360 gamepad object
  70937. * @param id defines the id of this gamepad
  70938. * @param index defines its index
  70939. * @param gamepad defines the internal HTML gamepad object
  70940. * @param xboxOne defines if it is a XBox One gamepad
  70941. */
  70942. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70943. if (xboxOne === void 0) { xboxOne = false; }
  70944. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70945. _this._leftTrigger = 0;
  70946. _this._rightTrigger = 0;
  70947. /** Observable raised when a button is pressed */
  70948. _this.onButtonDownObservable = new BABYLON.Observable();
  70949. /** Observable raised when a button is released */
  70950. _this.onButtonUpObservable = new BABYLON.Observable();
  70951. /** Observable raised when a pad is pressed */
  70952. _this.onPadDownObservable = new BABYLON.Observable();
  70953. /** Observable raised when a pad is released */
  70954. _this.onPadUpObservable = new BABYLON.Observable();
  70955. _this._buttonA = 0;
  70956. _this._buttonB = 0;
  70957. _this._buttonX = 0;
  70958. _this._buttonY = 0;
  70959. _this._buttonBack = 0;
  70960. _this._buttonStart = 0;
  70961. _this._buttonLB = 0;
  70962. _this._buttonRB = 0;
  70963. _this._buttonLeftStick = 0;
  70964. _this._buttonRightStick = 0;
  70965. _this._dPadUp = 0;
  70966. _this._dPadDown = 0;
  70967. _this._dPadLeft = 0;
  70968. _this._dPadRight = 0;
  70969. _this._isXboxOnePad = false;
  70970. _this.type = BABYLON.Gamepad.XBOX;
  70971. _this._isXboxOnePad = xboxOne;
  70972. return _this;
  70973. }
  70974. /**
  70975. * Defines the callback to call when left trigger is pressed
  70976. * @param callback defines the callback to use
  70977. */
  70978. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70979. this._onlefttriggerchanged = callback;
  70980. };
  70981. /**
  70982. * Defines the callback to call when right trigger is pressed
  70983. * @param callback defines the callback to use
  70984. */
  70985. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70986. this._onrighttriggerchanged = callback;
  70987. };
  70988. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70989. /**
  70990. * Gets or sets left trigger value
  70991. */
  70992. get: function () {
  70993. return this._leftTrigger;
  70994. },
  70995. set: function (newValue) {
  70996. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70997. this._onlefttriggerchanged(newValue);
  70998. }
  70999. this._leftTrigger = newValue;
  71000. },
  71001. enumerable: true,
  71002. configurable: true
  71003. });
  71004. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71005. /**
  71006. * Gets or sets right trigger value
  71007. */
  71008. get: function () {
  71009. return this._rightTrigger;
  71010. },
  71011. set: function (newValue) {
  71012. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71013. this._onrighttriggerchanged(newValue);
  71014. }
  71015. this._rightTrigger = newValue;
  71016. },
  71017. enumerable: true,
  71018. configurable: true
  71019. });
  71020. /**
  71021. * Defines the callback to call when a button is pressed
  71022. * @param callback defines the callback to use
  71023. */
  71024. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71025. this._onbuttondown = callback;
  71026. };
  71027. /**
  71028. * Defines the callback to call when a button is released
  71029. * @param callback defines the callback to use
  71030. */
  71031. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71032. this._onbuttonup = callback;
  71033. };
  71034. /**
  71035. * Defines the callback to call when a pad is pressed
  71036. * @param callback defines the callback to use
  71037. */
  71038. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71039. this._ondpaddown = callback;
  71040. };
  71041. /**
  71042. * Defines the callback to call when a pad is released
  71043. * @param callback defines the callback to use
  71044. */
  71045. Xbox360Pad.prototype.ondpadup = function (callback) {
  71046. this._ondpadup = callback;
  71047. };
  71048. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71049. if (newValue !== currentValue) {
  71050. if (newValue === 1) {
  71051. if (this._onbuttondown) {
  71052. this._onbuttondown(buttonType);
  71053. }
  71054. this.onButtonDownObservable.notifyObservers(buttonType);
  71055. }
  71056. if (newValue === 0) {
  71057. if (this._onbuttonup) {
  71058. this._onbuttonup(buttonType);
  71059. }
  71060. this.onButtonUpObservable.notifyObservers(buttonType);
  71061. }
  71062. }
  71063. return newValue;
  71064. };
  71065. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71066. if (newValue !== currentValue) {
  71067. if (newValue === 1) {
  71068. if (this._ondpaddown) {
  71069. this._ondpaddown(buttonType);
  71070. }
  71071. this.onPadDownObservable.notifyObservers(buttonType);
  71072. }
  71073. if (newValue === 0) {
  71074. if (this._ondpadup) {
  71075. this._ondpadup(buttonType);
  71076. }
  71077. this.onPadUpObservable.notifyObservers(buttonType);
  71078. }
  71079. }
  71080. return newValue;
  71081. };
  71082. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71083. /** Gets or sets value of A button */
  71084. get: function () {
  71085. return this._buttonA;
  71086. },
  71087. set: function (value) {
  71088. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71089. },
  71090. enumerable: true,
  71091. configurable: true
  71092. });
  71093. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71094. /** Gets or sets value of B button */
  71095. get: function () {
  71096. return this._buttonB;
  71097. },
  71098. set: function (value) {
  71099. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71100. },
  71101. enumerable: true,
  71102. configurable: true
  71103. });
  71104. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71105. /** Gets or sets value of X button */
  71106. get: function () {
  71107. return this._buttonX;
  71108. },
  71109. set: function (value) {
  71110. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71111. },
  71112. enumerable: true,
  71113. configurable: true
  71114. });
  71115. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71116. /** Gets or sets value of Y button */
  71117. get: function () {
  71118. return this._buttonY;
  71119. },
  71120. set: function (value) {
  71121. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71122. },
  71123. enumerable: true,
  71124. configurable: true
  71125. });
  71126. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71127. /** Gets or sets value of Start button */
  71128. get: function () {
  71129. return this._buttonStart;
  71130. },
  71131. set: function (value) {
  71132. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71133. },
  71134. enumerable: true,
  71135. configurable: true
  71136. });
  71137. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71138. /** Gets or sets value of Back button */
  71139. get: function () {
  71140. return this._buttonBack;
  71141. },
  71142. set: function (value) {
  71143. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71144. },
  71145. enumerable: true,
  71146. configurable: true
  71147. });
  71148. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71149. /** Gets or sets value of Left button */
  71150. get: function () {
  71151. return this._buttonLB;
  71152. },
  71153. set: function (value) {
  71154. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71155. },
  71156. enumerable: true,
  71157. configurable: true
  71158. });
  71159. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71160. /** Gets or sets value of Right button */
  71161. get: function () {
  71162. return this._buttonRB;
  71163. },
  71164. set: function (value) {
  71165. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71166. },
  71167. enumerable: true,
  71168. configurable: true
  71169. });
  71170. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71171. /** Gets or sets value of left stick */
  71172. get: function () {
  71173. return this._buttonLeftStick;
  71174. },
  71175. set: function (value) {
  71176. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71177. },
  71178. enumerable: true,
  71179. configurable: true
  71180. });
  71181. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71182. /** Gets or sets value of right stick */
  71183. get: function () {
  71184. return this._buttonRightStick;
  71185. },
  71186. set: function (value) {
  71187. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71188. },
  71189. enumerable: true,
  71190. configurable: true
  71191. });
  71192. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71193. /** Gets or sets value of DPad up */
  71194. get: function () {
  71195. return this._dPadUp;
  71196. },
  71197. set: function (value) {
  71198. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71199. },
  71200. enumerable: true,
  71201. configurable: true
  71202. });
  71203. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71204. /** Gets or sets value of DPad down */
  71205. get: function () {
  71206. return this._dPadDown;
  71207. },
  71208. set: function (value) {
  71209. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71210. },
  71211. enumerable: true,
  71212. configurable: true
  71213. });
  71214. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71215. /** Gets or sets value of DPad left */
  71216. get: function () {
  71217. return this._dPadLeft;
  71218. },
  71219. set: function (value) {
  71220. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71221. },
  71222. enumerable: true,
  71223. configurable: true
  71224. });
  71225. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71226. /** Gets or sets value of DPad right */
  71227. get: function () {
  71228. return this._dPadRight;
  71229. },
  71230. set: function (value) {
  71231. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71232. },
  71233. enumerable: true,
  71234. configurable: true
  71235. });
  71236. /**
  71237. * Force the gamepad to synchronize with device values
  71238. */
  71239. Xbox360Pad.prototype.update = function () {
  71240. _super.prototype.update.call(this);
  71241. if (this._isXboxOnePad) {
  71242. this.buttonA = this.browserGamepad.buttons[0].value;
  71243. this.buttonB = this.browserGamepad.buttons[1].value;
  71244. this.buttonX = this.browserGamepad.buttons[2].value;
  71245. this.buttonY = this.browserGamepad.buttons[3].value;
  71246. this.buttonLB = this.browserGamepad.buttons[4].value;
  71247. this.buttonRB = this.browserGamepad.buttons[5].value;
  71248. this.leftTrigger = this.browserGamepad.axes[2];
  71249. this.rightTrigger = this.browserGamepad.axes[5];
  71250. this.buttonBack = this.browserGamepad.buttons[9].value;
  71251. this.buttonStart = this.browserGamepad.buttons[8].value;
  71252. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71253. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71254. this.dPadUp = this.browserGamepad.buttons[11].value;
  71255. this.dPadDown = this.browserGamepad.buttons[12].value;
  71256. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71257. this.dPadRight = this.browserGamepad.buttons[14].value;
  71258. }
  71259. else {
  71260. this.buttonA = this.browserGamepad.buttons[0].value;
  71261. this.buttonB = this.browserGamepad.buttons[1].value;
  71262. this.buttonX = this.browserGamepad.buttons[2].value;
  71263. this.buttonY = this.browserGamepad.buttons[3].value;
  71264. this.buttonLB = this.browserGamepad.buttons[4].value;
  71265. this.buttonRB = this.browserGamepad.buttons[5].value;
  71266. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71267. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71268. this.buttonBack = this.browserGamepad.buttons[8].value;
  71269. this.buttonStart = this.browserGamepad.buttons[9].value;
  71270. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71271. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71272. this.dPadUp = this.browserGamepad.buttons[12].value;
  71273. this.dPadDown = this.browserGamepad.buttons[13].value;
  71274. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71275. this.dPadRight = this.browserGamepad.buttons[15].value;
  71276. }
  71277. };
  71278. Xbox360Pad.prototype.dispose = function () {
  71279. _super.prototype.dispose.call(this);
  71280. this.onButtonDownObservable.clear();
  71281. this.onButtonUpObservable.clear();
  71282. this.onPadDownObservable.clear();
  71283. this.onPadUpObservable.clear();
  71284. };
  71285. return Xbox360Pad;
  71286. }(BABYLON.Gamepad));
  71287. BABYLON.Xbox360Pad = Xbox360Pad;
  71288. })(BABYLON || (BABYLON = {}));
  71289. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71290. var BABYLON;
  71291. (function (BABYLON) {
  71292. /**
  71293. * Defines the types of pose enabled controllers that are supported
  71294. */
  71295. var PoseEnabledControllerType;
  71296. (function (PoseEnabledControllerType) {
  71297. /**
  71298. * HTC Vive
  71299. */
  71300. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71301. /**
  71302. * Oculus Rift
  71303. */
  71304. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71305. /**
  71306. * Windows mixed reality
  71307. */
  71308. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71309. /**
  71310. * Samsung gear VR
  71311. */
  71312. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71313. /**
  71314. * Google Daydream
  71315. */
  71316. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71317. /**
  71318. * Generic
  71319. */
  71320. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71321. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71322. /**
  71323. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71324. */
  71325. var PoseEnabledControllerHelper = /** @class */ (function () {
  71326. function PoseEnabledControllerHelper() {
  71327. }
  71328. /**
  71329. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71330. * @param vrGamepad the gamepad to initialized
  71331. * @returns a vr controller of the type the gamepad identified as
  71332. */
  71333. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71334. // Oculus Touch
  71335. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71336. return new BABYLON.OculusTouchController(vrGamepad);
  71337. }
  71338. // Windows Mixed Reality controllers
  71339. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71340. return new BABYLON.WindowsMotionController(vrGamepad);
  71341. }
  71342. // HTC Vive
  71343. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71344. return new BABYLON.ViveController(vrGamepad);
  71345. }
  71346. // Samsung/Oculus Gear VR or Oculus Go
  71347. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71348. return new BABYLON.GearVRController(vrGamepad);
  71349. }
  71350. // Google Daydream
  71351. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71352. return new BABYLON.DaydreamController(vrGamepad);
  71353. }
  71354. // Generic
  71355. else {
  71356. return new BABYLON.GenericController(vrGamepad);
  71357. }
  71358. };
  71359. return PoseEnabledControllerHelper;
  71360. }());
  71361. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71362. /**
  71363. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71364. */
  71365. var PoseEnabledController = /** @class */ (function (_super) {
  71366. __extends(PoseEnabledController, _super);
  71367. /**
  71368. * Creates a new PoseEnabledController from a gamepad
  71369. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71370. */
  71371. function PoseEnabledController(browserGamepad) {
  71372. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71373. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71374. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71375. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71376. /**
  71377. * The device position in babylon space
  71378. */
  71379. _this.devicePosition = BABYLON.Vector3.Zero();
  71380. /**
  71381. * The device rotation in babylon space
  71382. */
  71383. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71384. /**
  71385. * The scale factor of the device in babylon space
  71386. */
  71387. _this.deviceScaleFactor = 1;
  71388. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71389. /**
  71390. * Internal, matrix used to convert room space to babylon space
  71391. */
  71392. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71393. /**
  71394. * Node to be used when casting a ray from the controller
  71395. */
  71396. _this._pointingPoseNode = null;
  71397. _this._workingMatrix = BABYLON.Matrix.Identity();
  71398. /**
  71399. * @hidden
  71400. */
  71401. _this._meshAttachedObservable = new BABYLON.Observable();
  71402. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71403. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71404. _this.position = BABYLON.Vector3.Zero();
  71405. _this.rotationQuaternion = new BABYLON.Quaternion();
  71406. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71407. _this._calculatedRotation = new BABYLON.Quaternion();
  71408. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71409. return _this;
  71410. }
  71411. /**
  71412. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71413. */
  71414. PoseEnabledController.prototype.update = function () {
  71415. _super.prototype.update.call(this);
  71416. var pose = this.browserGamepad.pose;
  71417. this.updateFromDevice(pose);
  71418. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71419. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71420. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71421. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71422. if (this._mesh) {
  71423. this._mesh.position.copyFrom(this.devicePosition);
  71424. if (this._mesh.rotationQuaternion) {
  71425. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71426. }
  71427. }
  71428. };
  71429. /**
  71430. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71431. * @param poseData raw pose fromthe device
  71432. */
  71433. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71434. if (poseData) {
  71435. this.rawPose = poseData;
  71436. if (poseData.position) {
  71437. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71438. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71439. this._deviceRoomPosition.z *= -1;
  71440. }
  71441. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71442. this._calculatedPosition.addInPlace(this.position);
  71443. }
  71444. var pose = this.rawPose;
  71445. if (poseData.orientation && pose.orientation) {
  71446. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71447. if (this._mesh) {
  71448. if (this._mesh.getScene().useRightHandedSystem) {
  71449. this._deviceRoomRotationQuaternion.z *= -1;
  71450. this._deviceRoomRotationQuaternion.w *= -1;
  71451. }
  71452. else {
  71453. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71454. }
  71455. }
  71456. // if the camera is set, rotate to the camera's rotation
  71457. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71458. }
  71459. }
  71460. };
  71461. /**
  71462. * Attaches a mesh to the controller
  71463. * @param mesh the mesh to be attached
  71464. */
  71465. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71466. if (this._mesh) {
  71467. this._mesh.parent = null;
  71468. }
  71469. this._mesh = mesh;
  71470. if (this._poseControlledCamera) {
  71471. this._mesh.parent = this._poseControlledCamera;
  71472. }
  71473. if (!this._mesh.rotationQuaternion) {
  71474. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71475. }
  71476. // Sync controller mesh and pointing pose node's state with controller
  71477. this.update();
  71478. if (this._pointingPoseNode) {
  71479. var parents = [];
  71480. var obj = this._pointingPoseNode;
  71481. while (obj.parent) {
  71482. parents.push(obj.parent);
  71483. obj = obj.parent;
  71484. }
  71485. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71486. }
  71487. this._meshAttachedObservable.notifyObservers(mesh);
  71488. };
  71489. /**
  71490. * Attaches the controllers mesh to a camera
  71491. * @param camera the camera the mesh should be attached to
  71492. */
  71493. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71494. this._poseControlledCamera = camera;
  71495. if (this._mesh) {
  71496. this._mesh.parent = this._poseControlledCamera;
  71497. }
  71498. };
  71499. /**
  71500. * Disposes of the controller
  71501. */
  71502. PoseEnabledController.prototype.dispose = function () {
  71503. if (this._mesh) {
  71504. this._mesh.dispose();
  71505. }
  71506. this._mesh = null;
  71507. _super.prototype.dispose.call(this);
  71508. };
  71509. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71510. /**
  71511. * The mesh that is attached to the controller
  71512. */
  71513. get: function () {
  71514. return this._mesh;
  71515. },
  71516. enumerable: true,
  71517. configurable: true
  71518. });
  71519. /**
  71520. * Gets the ray of the controller in the direction the controller is pointing
  71521. * @param length the length the resulting ray should be
  71522. * @returns a ray in the direction the controller is pointing
  71523. */
  71524. PoseEnabledController.prototype.getForwardRay = function (length) {
  71525. if (length === void 0) { length = 100; }
  71526. if (!this.mesh) {
  71527. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71528. }
  71529. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71530. var origin = m.getTranslation();
  71531. var forward = new BABYLON.Vector3(0, 0, -1);
  71532. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71533. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71534. return new BABYLON.Ray(origin, direction, length);
  71535. };
  71536. /**
  71537. * Name of the child mesh that can be used to cast a ray from the controller
  71538. */
  71539. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71540. return PoseEnabledController;
  71541. }(BABYLON.Gamepad));
  71542. BABYLON.PoseEnabledController = PoseEnabledController;
  71543. })(BABYLON || (BABYLON = {}));
  71544. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71545. var BABYLON;
  71546. (function (BABYLON) {
  71547. /**
  71548. * Defines the WebVRController object that represents controllers tracked in 3D space
  71549. */
  71550. var WebVRController = /** @class */ (function (_super) {
  71551. __extends(WebVRController, _super);
  71552. /**
  71553. * Creates a new WebVRController from a gamepad
  71554. * @param vrGamepad the gamepad that the WebVRController should be created from
  71555. */
  71556. function WebVRController(vrGamepad) {
  71557. var _this = _super.call(this, vrGamepad) || this;
  71558. // Observables
  71559. /**
  71560. * Fired when the trigger state has changed
  71561. */
  71562. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71563. /**
  71564. * Fired when the main button state has changed
  71565. */
  71566. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71567. /**
  71568. * Fired when the secondary button state has changed
  71569. */
  71570. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71571. /**
  71572. * Fired when the pad state has changed
  71573. */
  71574. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71575. /**
  71576. * Fired when controllers stick values have changed
  71577. */
  71578. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71579. /**
  71580. * X and Y axis corrisponding to the controllers joystick
  71581. */
  71582. _this.pad = { x: 0, y: 0 };
  71583. // avoid GC, store state in a tmp object
  71584. _this._changes = {
  71585. pressChanged: false,
  71586. touchChanged: false,
  71587. valueChanged: false,
  71588. changed: false
  71589. };
  71590. _this._buttons = new Array(vrGamepad.buttons.length);
  71591. _this.hand = vrGamepad.hand;
  71592. return _this;
  71593. }
  71594. /**
  71595. * Fired when a controller button's state has changed
  71596. * @param callback the callback containing the button that was modified
  71597. */
  71598. WebVRController.prototype.onButtonStateChange = function (callback) {
  71599. this._onButtonStateChange = callback;
  71600. };
  71601. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71602. /**
  71603. * The default controller model for the controller
  71604. */
  71605. get: function () {
  71606. return this._defaultModel;
  71607. },
  71608. enumerable: true,
  71609. configurable: true
  71610. });
  71611. /**
  71612. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71613. */
  71614. WebVRController.prototype.update = function () {
  71615. _super.prototype.update.call(this);
  71616. for (var index = 0; index < this._buttons.length; index++) {
  71617. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71618. }
  71619. ;
  71620. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71621. this.pad.x = this.leftStick.x;
  71622. this.pad.y = this.leftStick.y;
  71623. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71624. }
  71625. };
  71626. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71627. if (!newState) {
  71628. newState = {
  71629. pressed: false,
  71630. touched: false,
  71631. value: 0
  71632. };
  71633. }
  71634. if (!currentState) {
  71635. this._buttons[buttonIndex] = {
  71636. pressed: newState.pressed,
  71637. touched: newState.touched,
  71638. value: newState.value
  71639. };
  71640. return;
  71641. }
  71642. this._checkChanges(newState, currentState);
  71643. if (this._changes.changed) {
  71644. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71645. this._handleButtonChange(buttonIndex, newState, this._changes);
  71646. }
  71647. this._buttons[buttonIndex].pressed = newState.pressed;
  71648. this._buttons[buttonIndex].touched = newState.touched;
  71649. // oculus triggers are never 0, thou not touched.
  71650. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71651. };
  71652. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71653. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71654. this._changes.touchChanged = newState.touched !== currentState.touched;
  71655. this._changes.valueChanged = newState.value !== currentState.value;
  71656. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71657. return this._changes;
  71658. };
  71659. /**
  71660. * Disposes of th webVRCOntroller
  71661. */
  71662. WebVRController.prototype.dispose = function () {
  71663. _super.prototype.dispose.call(this);
  71664. this.onTriggerStateChangedObservable.clear();
  71665. this.onMainButtonStateChangedObservable.clear();
  71666. this.onSecondaryButtonStateChangedObservable.clear();
  71667. this.onPadStateChangedObservable.clear();
  71668. this.onPadValuesChangedObservable.clear();
  71669. };
  71670. return WebVRController;
  71671. }(BABYLON.PoseEnabledController));
  71672. BABYLON.WebVRController = WebVRController;
  71673. })(BABYLON || (BABYLON = {}));
  71674. //# sourceMappingURL=babylon.webVRController.js.map
  71675. var BABYLON;
  71676. (function (BABYLON) {
  71677. /**
  71678. * Oculus Touch Controller
  71679. */
  71680. var OculusTouchController = /** @class */ (function (_super) {
  71681. __extends(OculusTouchController, _super);
  71682. /**
  71683. * Creates a new OculusTouchController from a gamepad
  71684. * @param vrGamepad the gamepad that the controller should be created from
  71685. */
  71686. function OculusTouchController(vrGamepad) {
  71687. var _this = _super.call(this, vrGamepad) || this;
  71688. /**
  71689. * Fired when the secondary trigger on this controller is modified
  71690. */
  71691. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71692. /**
  71693. * Fired when the thumb rest on this controller is modified
  71694. */
  71695. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71696. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71697. return _this;
  71698. }
  71699. /**
  71700. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71701. * @param scene scene in which to add meshes
  71702. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71703. */
  71704. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71705. var _this = this;
  71706. var meshName;
  71707. // Hand
  71708. if (this.hand === 'left') {
  71709. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71710. }
  71711. else { // Right is the default if no hand is specified
  71712. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71713. }
  71714. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71715. /*
  71716. Parent Mesh name: oculus_touch_left
  71717. - body
  71718. - trigger
  71719. - thumbstick
  71720. - grip
  71721. - button_y
  71722. - button_x
  71723. - button_enter
  71724. */
  71725. _this._defaultModel = newMeshes[1];
  71726. _this.attachToMesh(_this._defaultModel);
  71727. if (meshLoaded) {
  71728. meshLoaded(_this._defaultModel);
  71729. }
  71730. });
  71731. };
  71732. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71733. /**
  71734. * Fired when the A button on this controller is modified
  71735. */
  71736. get: function () {
  71737. if (this.hand === 'right') {
  71738. return this.onMainButtonStateChangedObservable;
  71739. }
  71740. else {
  71741. throw new Error('No A button on left hand');
  71742. }
  71743. },
  71744. enumerable: true,
  71745. configurable: true
  71746. });
  71747. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71748. /**
  71749. * Fired when the B button on this controller is modified
  71750. */
  71751. get: function () {
  71752. if (this.hand === 'right') {
  71753. return this.onSecondaryButtonStateChangedObservable;
  71754. }
  71755. else {
  71756. throw new Error('No B button on left hand');
  71757. }
  71758. },
  71759. enumerable: true,
  71760. configurable: true
  71761. });
  71762. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71763. /**
  71764. * Fired when the X button on this controller is modified
  71765. */
  71766. get: function () {
  71767. if (this.hand === 'left') {
  71768. return this.onMainButtonStateChangedObservable;
  71769. }
  71770. else {
  71771. throw new Error('No X button on right hand');
  71772. }
  71773. },
  71774. enumerable: true,
  71775. configurable: true
  71776. });
  71777. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71778. /**
  71779. * Fired when the Y button on this controller is modified
  71780. */
  71781. get: function () {
  71782. if (this.hand === 'left') {
  71783. return this.onSecondaryButtonStateChangedObservable;
  71784. }
  71785. else {
  71786. throw new Error('No Y button on right hand');
  71787. }
  71788. },
  71789. enumerable: true,
  71790. configurable: true
  71791. });
  71792. /**
  71793. * Called once for each button that changed state since the last frame
  71794. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71795. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71796. * 2) secondary trigger (same)
  71797. * 3) A (right) X (left), touch, pressed = value
  71798. * 4) B / Y
  71799. * 5) thumb rest
  71800. * @param buttonIdx Which button index changed
  71801. * @param state New state of the button
  71802. * @param changes Which properties on the state changed since last frame
  71803. */
  71804. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71805. var notifyObject = state; //{ state: state, changes: changes };
  71806. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71807. switch (buttonIdx) {
  71808. case 0:
  71809. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71810. return;
  71811. case 1: // index trigger
  71812. if (this._defaultModel) {
  71813. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71814. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71815. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71816. }
  71817. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71818. return;
  71819. case 2: // secondary trigger
  71820. if (this._defaultModel) {
  71821. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71822. }
  71823. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71824. return;
  71825. case 3:
  71826. if (this._defaultModel) {
  71827. if (notifyObject.pressed) {
  71828. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71829. }
  71830. else {
  71831. (this._defaultModel.getChildren()[1]).position.y = 0;
  71832. }
  71833. }
  71834. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71835. return;
  71836. case 4:
  71837. if (this._defaultModel) {
  71838. if (notifyObject.pressed) {
  71839. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71840. }
  71841. else {
  71842. (this._defaultModel.getChildren()[2]).position.y = 0;
  71843. }
  71844. }
  71845. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71846. return;
  71847. case 5:
  71848. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71849. return;
  71850. }
  71851. };
  71852. /**
  71853. * Base Url for the controller model.
  71854. */
  71855. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71856. /**
  71857. * File name for the left controller model.
  71858. */
  71859. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71860. /**
  71861. * File name for the right controller model.
  71862. */
  71863. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71864. return OculusTouchController;
  71865. }(BABYLON.WebVRController));
  71866. BABYLON.OculusTouchController = OculusTouchController;
  71867. })(BABYLON || (BABYLON = {}));
  71868. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71869. var BABYLON;
  71870. (function (BABYLON) {
  71871. /**
  71872. * Vive Controller
  71873. */
  71874. var ViveController = /** @class */ (function (_super) {
  71875. __extends(ViveController, _super);
  71876. /**
  71877. * Creates a new ViveController from a gamepad
  71878. * @param vrGamepad the gamepad that the controller should be created from
  71879. */
  71880. function ViveController(vrGamepad) {
  71881. var _this = _super.call(this, vrGamepad) || this;
  71882. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71883. _this._invertLeftStickY = true;
  71884. return _this;
  71885. }
  71886. /**
  71887. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71888. * @param scene scene in which to add meshes
  71889. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71890. */
  71891. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71892. var _this = this;
  71893. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71894. /*
  71895. Parent Mesh name: ViveWand
  71896. - body
  71897. - r_gripper
  71898. - l_gripper
  71899. - menu_button
  71900. - system_button
  71901. - trackpad
  71902. - trigger
  71903. - LED
  71904. */
  71905. _this._defaultModel = newMeshes[1];
  71906. _this.attachToMesh(_this._defaultModel);
  71907. if (meshLoaded) {
  71908. meshLoaded(_this._defaultModel);
  71909. }
  71910. });
  71911. };
  71912. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71913. /**
  71914. * Fired when the left button on this controller is modified
  71915. */
  71916. get: function () {
  71917. return this.onMainButtonStateChangedObservable;
  71918. },
  71919. enumerable: true,
  71920. configurable: true
  71921. });
  71922. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71923. /**
  71924. * Fired when the right button on this controller is modified
  71925. */
  71926. get: function () {
  71927. return this.onMainButtonStateChangedObservable;
  71928. },
  71929. enumerable: true,
  71930. configurable: true
  71931. });
  71932. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71933. /**
  71934. * Fired when the menu button on this controller is modified
  71935. */
  71936. get: function () {
  71937. return this.onSecondaryButtonStateChangedObservable;
  71938. },
  71939. enumerable: true,
  71940. configurable: true
  71941. });
  71942. /**
  71943. * Called once for each button that changed state since the last frame
  71944. * Vive mapping:
  71945. * 0: touchpad
  71946. * 1: trigger
  71947. * 2: left AND right buttons
  71948. * 3: menu button
  71949. * @param buttonIdx Which button index changed
  71950. * @param state New state of the button
  71951. * @param changes Which properties on the state changed since last frame
  71952. */
  71953. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71954. var notifyObject = state; //{ state: state, changes: changes };
  71955. switch (buttonIdx) {
  71956. case 0:
  71957. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71958. return;
  71959. case 1: // index trigger
  71960. if (this._defaultModel) {
  71961. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71962. }
  71963. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71964. return;
  71965. case 2: // left AND right button
  71966. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71967. return;
  71968. case 3:
  71969. if (this._defaultModel) {
  71970. if (notifyObject.pressed) {
  71971. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71972. }
  71973. else {
  71974. (this._defaultModel.getChildren()[2]).position.y = 0;
  71975. }
  71976. }
  71977. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71978. return;
  71979. }
  71980. };
  71981. /**
  71982. * Base Url for the controller model.
  71983. */
  71984. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71985. /**
  71986. * File name for the controller model.
  71987. */
  71988. ViveController.MODEL_FILENAME = 'wand.babylon';
  71989. return ViveController;
  71990. }(BABYLON.WebVRController));
  71991. BABYLON.ViveController = ViveController;
  71992. })(BABYLON || (BABYLON = {}));
  71993. //# sourceMappingURL=babylon.viveController.js.map
  71994. var BABYLON;
  71995. (function (BABYLON) {
  71996. /**
  71997. * Generic Controller
  71998. */
  71999. var GenericController = /** @class */ (function (_super) {
  72000. __extends(GenericController, _super);
  72001. /**
  72002. * Creates a new GenericController from a gamepad
  72003. * @param vrGamepad the gamepad that the controller should be created from
  72004. */
  72005. function GenericController(vrGamepad) {
  72006. return _super.call(this, vrGamepad) || this;
  72007. }
  72008. /**
  72009. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72010. * @param scene scene in which to add meshes
  72011. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72012. */
  72013. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72014. var _this = this;
  72015. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72016. _this._defaultModel = newMeshes[1];
  72017. _this.attachToMesh(_this._defaultModel);
  72018. if (meshLoaded) {
  72019. meshLoaded(_this._defaultModel);
  72020. }
  72021. });
  72022. };
  72023. /**
  72024. * Called once for each button that changed state since the last frame
  72025. * @param buttonIdx Which button index changed
  72026. * @param state New state of the button
  72027. * @param changes Which properties on the state changed since last frame
  72028. */
  72029. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72030. console.log("Button id: " + buttonIdx + "state: ");
  72031. console.dir(state);
  72032. };
  72033. /**
  72034. * Base Url for the controller model.
  72035. */
  72036. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72037. /**
  72038. * File name for the controller model.
  72039. */
  72040. GenericController.MODEL_FILENAME = 'generic.babylon';
  72041. return GenericController;
  72042. }(BABYLON.WebVRController));
  72043. BABYLON.GenericController = GenericController;
  72044. })(BABYLON || (BABYLON = {}));
  72045. //# sourceMappingURL=babylon.genericController.js.map
  72046. var BABYLON;
  72047. (function (BABYLON) {
  72048. /**
  72049. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72050. */
  72051. var LoadedMeshInfo = /** @class */ (function () {
  72052. function LoadedMeshInfo() {
  72053. /**
  72054. * Map of the button meshes contained in the controller
  72055. */
  72056. this.buttonMeshes = {};
  72057. /**
  72058. * Map of the axis meshes contained in the controller
  72059. */
  72060. this.axisMeshes = {};
  72061. }
  72062. return LoadedMeshInfo;
  72063. }());
  72064. /**
  72065. * Defines the WindowsMotionController object that the state of the windows motion controller
  72066. */
  72067. var WindowsMotionController = /** @class */ (function (_super) {
  72068. __extends(WindowsMotionController, _super);
  72069. /**
  72070. * Creates a new WindowsMotionController from a gamepad
  72071. * @param vrGamepad the gamepad that the controller should be created from
  72072. */
  72073. function WindowsMotionController(vrGamepad) {
  72074. var _this = _super.call(this, vrGamepad) || this;
  72075. _this._mapping = {
  72076. // Semantic button names
  72077. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72078. // A mapping of the button name to glTF model node name
  72079. // that should be transformed by button value.
  72080. buttonMeshNames: {
  72081. 'trigger': 'SELECT',
  72082. 'menu': 'MENU',
  72083. 'grip': 'GRASP',
  72084. 'thumbstick': 'THUMBSTICK_PRESS',
  72085. 'trackpad': 'TOUCHPAD_PRESS'
  72086. },
  72087. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72088. buttonObservableNames: {
  72089. 'trigger': 'onTriggerStateChangedObservable',
  72090. 'menu': 'onSecondaryButtonStateChangedObservable',
  72091. 'grip': 'onMainButtonStateChangedObservable',
  72092. 'thumbstick': 'onPadStateChangedObservable',
  72093. 'trackpad': 'onTrackpadChangedObservable'
  72094. },
  72095. // A mapping of the axis name to glTF model node name
  72096. // that should be transformed by axis value.
  72097. // This array mirrors the browserGamepad.axes array, such that
  72098. // the mesh corresponding to axis 0 is in this array index 0.
  72099. axisMeshNames: [
  72100. 'THUMBSTICK_X',
  72101. 'THUMBSTICK_Y',
  72102. 'TOUCHPAD_TOUCH_X',
  72103. 'TOUCHPAD_TOUCH_Y'
  72104. ],
  72105. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72106. };
  72107. /**
  72108. * Fired when the trackpad on this controller is clicked
  72109. */
  72110. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72111. /**
  72112. * Fired when the trackpad on this controller is modified
  72113. */
  72114. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72115. /**
  72116. * The current x and y values of this controller's trackpad
  72117. */
  72118. _this.trackpad = { x: 0, y: 0 };
  72119. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72120. _this._loadedMeshInfo = null;
  72121. return _this;
  72122. }
  72123. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72124. /**
  72125. * Fired when the trigger on this controller is modified
  72126. */
  72127. get: function () {
  72128. return this.onTriggerStateChangedObservable;
  72129. },
  72130. enumerable: true,
  72131. configurable: true
  72132. });
  72133. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72134. /**
  72135. * Fired when the menu button on this controller is modified
  72136. */
  72137. get: function () {
  72138. return this.onSecondaryButtonStateChangedObservable;
  72139. },
  72140. enumerable: true,
  72141. configurable: true
  72142. });
  72143. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72144. /**
  72145. * Fired when the grip button on this controller is modified
  72146. */
  72147. get: function () {
  72148. return this.onMainButtonStateChangedObservable;
  72149. },
  72150. enumerable: true,
  72151. configurable: true
  72152. });
  72153. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72154. /**
  72155. * Fired when the thumbstick button on this controller is modified
  72156. */
  72157. get: function () {
  72158. return this.onPadStateChangedObservable;
  72159. },
  72160. enumerable: true,
  72161. configurable: true
  72162. });
  72163. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72164. /**
  72165. * Fired when the touchpad button on this controller is modified
  72166. */
  72167. get: function () {
  72168. return this.onTrackpadChangedObservable;
  72169. },
  72170. enumerable: true,
  72171. configurable: true
  72172. });
  72173. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72174. /**
  72175. * Fired when the touchpad values on this controller are modified
  72176. */
  72177. get: function () {
  72178. return this.onTrackpadValuesChangedObservable;
  72179. },
  72180. enumerable: true,
  72181. configurable: true
  72182. });
  72183. WindowsMotionController.prototype._updateTrackpad = function () {
  72184. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72185. this.trackpad.x = this.browserGamepad["axes"][2];
  72186. this.trackpad.y = this.browserGamepad["axes"][3];
  72187. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72188. }
  72189. };
  72190. /**
  72191. * Called once per frame by the engine.
  72192. */
  72193. WindowsMotionController.prototype.update = function () {
  72194. _super.prototype.update.call(this);
  72195. if (this.browserGamepad.axes) {
  72196. this._updateTrackpad();
  72197. // Only need to animate axes if there is a loaded mesh
  72198. if (this._loadedMeshInfo) {
  72199. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72200. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72201. }
  72202. }
  72203. }
  72204. };
  72205. /**
  72206. * Called once for each button that changed state since the last frame
  72207. * @param buttonIdx Which button index changed
  72208. * @param state New state of the button
  72209. * @param changes Which properties on the state changed since last frame
  72210. */
  72211. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72212. var buttonName = this._mapping.buttons[buttonIdx];
  72213. if (!buttonName) {
  72214. return;
  72215. }
  72216. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72217. this._updateTrackpad();
  72218. // Only emit events for buttons that we know how to map from index to name
  72219. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72220. if (observable) {
  72221. observable.notifyObservers(state);
  72222. }
  72223. this._lerpButtonTransform(buttonName, state.value);
  72224. };
  72225. /**
  72226. * Moves the buttons on the controller mesh based on their current state
  72227. * @param buttonName the name of the button to move
  72228. * @param buttonValue the value of the button which determines the buttons new position
  72229. */
  72230. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72231. // If there is no loaded mesh, there is nothing to transform.
  72232. if (!this._loadedMeshInfo) {
  72233. return;
  72234. }
  72235. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72236. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72237. return;
  72238. }
  72239. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72240. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72241. };
  72242. /**
  72243. * Moves the axis on the controller mesh based on its current state
  72244. * @param axis the index of the axis
  72245. * @param axisValue the value of the axis which determines the meshes new position
  72246. * @hidden
  72247. */
  72248. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72249. if (!this._loadedMeshInfo) {
  72250. return;
  72251. }
  72252. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72253. if (!meshInfo) {
  72254. return;
  72255. }
  72256. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72257. return;
  72258. }
  72259. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72260. var lerpValue = axisValue * 0.5 + 0.5;
  72261. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72262. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72263. };
  72264. /**
  72265. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72266. * @param scene scene in which to add meshes
  72267. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72268. */
  72269. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72270. var _this = this;
  72271. if (forceDefault === void 0) { forceDefault = false; }
  72272. var path;
  72273. var filename;
  72274. // Checking if GLB loader is present
  72275. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72276. // Determine the device specific folder based on the ID suffix
  72277. var device = 'default';
  72278. if (this.id && !forceDefault) {
  72279. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72280. device = ((match && match[0]) || device);
  72281. }
  72282. // Hand
  72283. if (this.hand === 'left') {
  72284. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72285. }
  72286. else { // Right is the default if no hand is specified
  72287. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72288. }
  72289. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72290. }
  72291. else {
  72292. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72293. path = BABYLON.GenericController.MODEL_BASE_URL;
  72294. filename = BABYLON.GenericController.MODEL_FILENAME;
  72295. }
  72296. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72297. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72298. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72299. if (!_this._loadedMeshInfo) {
  72300. return;
  72301. }
  72302. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72303. _this.attachToMesh(_this._defaultModel);
  72304. if (meshLoaded) {
  72305. meshLoaded(_this._defaultModel);
  72306. }
  72307. }, null, function (scene, message) {
  72308. BABYLON.Tools.Log(message);
  72309. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72310. if (!forceDefault) {
  72311. _this.initControllerMesh(scene, meshLoaded, true);
  72312. }
  72313. });
  72314. };
  72315. /**
  72316. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72317. * can be transformed by button presses and axes values, based on this._mapping.
  72318. *
  72319. * @param scene scene in which the meshes exist
  72320. * @param meshes list of meshes that make up the controller model to process
  72321. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72322. */
  72323. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72324. var loadedMeshInfo = null;
  72325. // Create a new mesh to contain the glTF hierarchy
  72326. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72327. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72328. var childMesh = null;
  72329. for (var i = 0; i < meshes.length; i++) {
  72330. var mesh = meshes[i];
  72331. if (!mesh.parent) {
  72332. // Exclude controller meshes from picking results
  72333. mesh.isPickable = false;
  72334. // Handle root node, attach to the new parentMesh
  72335. childMesh = mesh;
  72336. break;
  72337. }
  72338. }
  72339. if (childMesh) {
  72340. childMesh.setParent(parentMesh);
  72341. // Create our mesh info. Note that this method will always return non-null.
  72342. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72343. }
  72344. else {
  72345. BABYLON.Tools.Warn('Could not find root node in model file.');
  72346. }
  72347. return loadedMeshInfo;
  72348. };
  72349. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72350. var loadedMeshInfo = new LoadedMeshInfo();
  72351. var i;
  72352. loadedMeshInfo.rootNode = rootNode;
  72353. // Reset the caches
  72354. loadedMeshInfo.buttonMeshes = {};
  72355. loadedMeshInfo.axisMeshes = {};
  72356. // Button Meshes
  72357. for (i = 0; i < this._mapping.buttons.length; i++) {
  72358. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72359. if (!buttonMeshName) {
  72360. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72361. continue;
  72362. }
  72363. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72364. if (!buttonMesh) {
  72365. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72366. continue;
  72367. }
  72368. var buttonMeshInfo = {
  72369. index: i,
  72370. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72371. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72372. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72373. };
  72374. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72375. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72376. }
  72377. else {
  72378. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72379. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72380. '(VALUE: ' + !!buttonMeshInfo.value +
  72381. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72382. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72383. ')');
  72384. }
  72385. }
  72386. // Axis Meshes
  72387. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72388. var axisMeshName = this._mapping.axisMeshNames[i];
  72389. if (!axisMeshName) {
  72390. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72391. continue;
  72392. }
  72393. var axisMesh = getChildByName(rootNode, axisMeshName);
  72394. if (!axisMesh) {
  72395. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72396. continue;
  72397. }
  72398. var axisMeshInfo = {
  72399. index: i,
  72400. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72401. min: getImmediateChildByName(axisMesh, 'MIN'),
  72402. max: getImmediateChildByName(axisMesh, 'MAX')
  72403. };
  72404. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72405. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72406. }
  72407. else {
  72408. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72409. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72410. '(VALUE: ' + !!axisMeshInfo.value +
  72411. ', MIN: ' + !!axisMeshInfo.min +
  72412. ', MAX:' + !!axisMeshInfo.max +
  72413. ')');
  72414. }
  72415. }
  72416. // Pointing Ray
  72417. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72418. if (!loadedMeshInfo.pointingPoseNode) {
  72419. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72420. }
  72421. else {
  72422. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72423. }
  72424. return loadedMeshInfo;
  72425. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72426. function getChildByName(node, name) {
  72427. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72428. }
  72429. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72430. function getImmediateChildByName(node, name) {
  72431. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72432. }
  72433. };
  72434. /**
  72435. * Gets the ray of the controller in the direction the controller is pointing
  72436. * @param length the length the resulting ray should be
  72437. * @returns a ray in the direction the controller is pointing
  72438. */
  72439. WindowsMotionController.prototype.getForwardRay = function (length) {
  72440. if (length === void 0) { length = 100; }
  72441. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72442. return _super.prototype.getForwardRay.call(this, length);
  72443. }
  72444. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72445. var origin = m.getTranslation();
  72446. var forward = new BABYLON.Vector3(0, 0, -1);
  72447. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72448. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72449. return new BABYLON.Ray(origin, direction, length);
  72450. };
  72451. /**
  72452. * Disposes of the controller
  72453. */
  72454. WindowsMotionController.prototype.dispose = function () {
  72455. _super.prototype.dispose.call(this);
  72456. this.onTrackpadChangedObservable.clear();
  72457. };
  72458. /**
  72459. * The base url used to load the left and right controller models
  72460. */
  72461. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72462. /**
  72463. * The name of the left controller model file
  72464. */
  72465. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72466. /**
  72467. * The name of the right controller model file
  72468. */
  72469. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72470. /**
  72471. * The controller name prefix for this controller type
  72472. */
  72473. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72474. /**
  72475. * The controller id pattern for this controller type
  72476. */
  72477. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72478. return WindowsMotionController;
  72479. }(BABYLON.WebVRController));
  72480. BABYLON.WindowsMotionController = WindowsMotionController;
  72481. })(BABYLON || (BABYLON = {}));
  72482. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72483. var BABYLON;
  72484. (function (BABYLON) {
  72485. /**
  72486. * Gear VR Controller
  72487. */
  72488. var GearVRController = /** @class */ (function (_super) {
  72489. __extends(GearVRController, _super);
  72490. /**
  72491. * Creates a new GearVRController from a gamepad
  72492. * @param vrGamepad the gamepad that the controller should be created from
  72493. */
  72494. function GearVRController(vrGamepad) {
  72495. var _this = _super.call(this, vrGamepad) || this;
  72496. _this._buttonIndexToObservableNameMap = [
  72497. 'onTrackpadChangedObservable',
  72498. 'onTriggerStateChangedObservable' // Trigger
  72499. ];
  72500. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72501. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72502. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72503. return _this;
  72504. }
  72505. /**
  72506. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72507. * @param scene scene in which to add meshes
  72508. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72509. */
  72510. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72511. var _this = this;
  72512. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72513. _this._defaultModel = newMeshes[1];
  72514. _this.attachToMesh(_this._defaultModel);
  72515. if (meshLoaded) {
  72516. meshLoaded(_this._defaultModel);
  72517. }
  72518. });
  72519. };
  72520. /**
  72521. * Called once for each button that changed state since the last frame
  72522. * @param buttonIdx Which button index changed
  72523. * @param state New state of the button
  72524. * @param changes Which properties on the state changed since last frame
  72525. */
  72526. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72527. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72528. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72529. // Only emit events for buttons that we know how to map from index to observable
  72530. var observable = this[observableName];
  72531. if (observable) {
  72532. observable.notifyObservers(state);
  72533. }
  72534. }
  72535. };
  72536. /**
  72537. * Base Url for the controller model.
  72538. */
  72539. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72540. /**
  72541. * File name for the controller model.
  72542. */
  72543. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72544. /**
  72545. * Gamepad Id prefix used to identify this controller.
  72546. */
  72547. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72548. return GearVRController;
  72549. }(BABYLON.WebVRController));
  72550. BABYLON.GearVRController = GearVRController;
  72551. })(BABYLON || (BABYLON = {}));
  72552. //# sourceMappingURL=babylon.gearVRController.js.map
  72553. var BABYLON;
  72554. (function (BABYLON) {
  72555. /**
  72556. * Google Daydream controller
  72557. */
  72558. var DaydreamController = /** @class */ (function (_super) {
  72559. __extends(DaydreamController, _super);
  72560. /**
  72561. * Creates a new DaydreamController from a gamepad
  72562. * @param vrGamepad the gamepad that the controller should be created from
  72563. */
  72564. function DaydreamController(vrGamepad) {
  72565. var _this = _super.call(this, vrGamepad) || this;
  72566. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72567. return _this;
  72568. }
  72569. /**
  72570. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72571. * @param scene scene in which to add meshes
  72572. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72573. */
  72574. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72575. var _this = this;
  72576. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72577. _this._defaultModel = newMeshes[1];
  72578. _this.attachToMesh(_this._defaultModel);
  72579. if (meshLoaded) {
  72580. meshLoaded(_this._defaultModel);
  72581. }
  72582. });
  72583. };
  72584. /**
  72585. * Called once for each button that changed state since the last frame
  72586. * @param buttonIdx Which button index changed
  72587. * @param state New state of the button
  72588. * @param changes Which properties on the state changed since last frame
  72589. */
  72590. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72591. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72592. if (buttonIdx === 0) {
  72593. var observable = this.onTriggerStateChangedObservable;
  72594. if (observable) {
  72595. observable.notifyObservers(state);
  72596. }
  72597. }
  72598. else {
  72599. // If the app or home buttons are ever made available
  72600. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72601. }
  72602. };
  72603. /**
  72604. * Base Url for the controller model.
  72605. */
  72606. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72607. /**
  72608. * File name for the controller model.
  72609. */
  72610. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72611. /**
  72612. * Gamepad Id prefix used to identify Daydream Controller.
  72613. */
  72614. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72615. return DaydreamController;
  72616. }(BABYLON.WebVRController));
  72617. BABYLON.DaydreamController = DaydreamController;
  72618. })(BABYLON || (BABYLON = {}));
  72619. //# sourceMappingURL=babylon.daydreamController.js.map
  72620. var BABYLON;
  72621. (function (BABYLON) {
  72622. var FollowCamera = /** @class */ (function (_super) {
  72623. __extends(FollowCamera, _super);
  72624. function FollowCamera(name, position, scene, lockedTarget) {
  72625. if (lockedTarget === void 0) { lockedTarget = null; }
  72626. var _this = _super.call(this, name, position, scene) || this;
  72627. _this.radius = 12;
  72628. _this.rotationOffset = 0;
  72629. _this.heightOffset = 4;
  72630. _this.cameraAcceleration = 0.05;
  72631. _this.maxCameraSpeed = 20;
  72632. _this.lockedTarget = lockedTarget;
  72633. return _this;
  72634. }
  72635. FollowCamera.prototype.getRadians = function (degrees) {
  72636. return degrees * Math.PI / 180;
  72637. };
  72638. FollowCamera.prototype.follow = function (cameraTarget) {
  72639. if (!cameraTarget)
  72640. return;
  72641. var yRotation;
  72642. if (cameraTarget.rotationQuaternion) {
  72643. var rotMatrix = new BABYLON.Matrix();
  72644. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72645. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72646. }
  72647. else {
  72648. yRotation = cameraTarget.rotation.y;
  72649. }
  72650. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72651. var targetPosition = cameraTarget.getAbsolutePosition();
  72652. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72653. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72654. var dx = targetX - this.position.x;
  72655. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72656. var dz = (targetZ) - this.position.z;
  72657. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72658. var vy = dy * this.cameraAcceleration;
  72659. var vz = dz * this.cameraAcceleration * 2;
  72660. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72661. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72662. }
  72663. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72664. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72665. }
  72666. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72667. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72668. }
  72669. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72670. this.setTarget(targetPosition);
  72671. };
  72672. FollowCamera.prototype._checkInputs = function () {
  72673. _super.prototype._checkInputs.call(this);
  72674. if (this.lockedTarget) {
  72675. this.follow(this.lockedTarget);
  72676. }
  72677. };
  72678. FollowCamera.prototype.getClassName = function () {
  72679. return "FollowCamera";
  72680. };
  72681. __decorate([
  72682. BABYLON.serialize()
  72683. ], FollowCamera.prototype, "radius", void 0);
  72684. __decorate([
  72685. BABYLON.serialize()
  72686. ], FollowCamera.prototype, "rotationOffset", void 0);
  72687. __decorate([
  72688. BABYLON.serialize()
  72689. ], FollowCamera.prototype, "heightOffset", void 0);
  72690. __decorate([
  72691. BABYLON.serialize()
  72692. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72693. __decorate([
  72694. BABYLON.serialize()
  72695. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72696. __decorate([
  72697. BABYLON.serializeAsMeshReference("lockedTargetId")
  72698. ], FollowCamera.prototype, "lockedTarget", void 0);
  72699. return FollowCamera;
  72700. }(BABYLON.TargetCamera));
  72701. BABYLON.FollowCamera = FollowCamera;
  72702. var ArcFollowCamera = /** @class */ (function (_super) {
  72703. __extends(ArcFollowCamera, _super);
  72704. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72705. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72706. _this.alpha = alpha;
  72707. _this.beta = beta;
  72708. _this.radius = radius;
  72709. _this.target = target;
  72710. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72711. _this.follow();
  72712. return _this;
  72713. }
  72714. ArcFollowCamera.prototype.follow = function () {
  72715. if (!this.target) {
  72716. return;
  72717. }
  72718. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72719. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72720. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72721. var targetPosition = this.target.getAbsolutePosition();
  72722. this.position = targetPosition.add(this._cartesianCoordinates);
  72723. this.setTarget(targetPosition);
  72724. };
  72725. ArcFollowCamera.prototype._checkInputs = function () {
  72726. _super.prototype._checkInputs.call(this);
  72727. this.follow();
  72728. };
  72729. ArcFollowCamera.prototype.getClassName = function () {
  72730. return "ArcFollowCamera";
  72731. };
  72732. return ArcFollowCamera;
  72733. }(BABYLON.TargetCamera));
  72734. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72735. })(BABYLON || (BABYLON = {}));
  72736. //# sourceMappingURL=babylon.followCamera.js.map
  72737. var BABYLON;
  72738. (function (BABYLON) {
  72739. // We're mainly based on the logic defined into the FreeCamera code
  72740. var UniversalCamera = /** @class */ (function (_super) {
  72741. __extends(UniversalCamera, _super);
  72742. //-- end properties for backward compatibility for inputs
  72743. function UniversalCamera(name, position, scene) {
  72744. var _this = _super.call(this, name, position, scene) || this;
  72745. _this.inputs.addGamepad();
  72746. return _this;
  72747. }
  72748. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72749. //-- Begin properties for backward compatibility for inputs
  72750. get: function () {
  72751. var gamepad = this.inputs.attached["gamepad"];
  72752. if (gamepad)
  72753. return gamepad.gamepadAngularSensibility;
  72754. return 0;
  72755. },
  72756. set: function (value) {
  72757. var gamepad = this.inputs.attached["gamepad"];
  72758. if (gamepad)
  72759. gamepad.gamepadAngularSensibility = value;
  72760. },
  72761. enumerable: true,
  72762. configurable: true
  72763. });
  72764. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72765. get: function () {
  72766. var gamepad = this.inputs.attached["gamepad"];
  72767. if (gamepad)
  72768. return gamepad.gamepadMoveSensibility;
  72769. return 0;
  72770. },
  72771. set: function (value) {
  72772. var gamepad = this.inputs.attached["gamepad"];
  72773. if (gamepad)
  72774. gamepad.gamepadMoveSensibility = value;
  72775. },
  72776. enumerable: true,
  72777. configurable: true
  72778. });
  72779. UniversalCamera.prototype.getClassName = function () {
  72780. return "UniversalCamera";
  72781. };
  72782. return UniversalCamera;
  72783. }(BABYLON.TouchCamera));
  72784. BABYLON.UniversalCamera = UniversalCamera;
  72785. })(BABYLON || (BABYLON = {}));
  72786. //# sourceMappingURL=babylon.universalCamera.js.map
  72787. var BABYLON;
  72788. (function (BABYLON) {
  72789. // We're mainly based on the logic defined into the FreeCamera code
  72790. var GamepadCamera = /** @class */ (function (_super) {
  72791. __extends(GamepadCamera, _super);
  72792. //-- end properties for backward compatibility for inputs
  72793. function GamepadCamera(name, position, scene) {
  72794. return _super.call(this, name, position, scene) || this;
  72795. }
  72796. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72797. //-- Begin properties for backward compatibility for inputs
  72798. get: function () {
  72799. var gamepad = this.inputs.attached["gamepad"];
  72800. if (gamepad)
  72801. return gamepad.gamepadAngularSensibility;
  72802. return 0;
  72803. },
  72804. set: function (value) {
  72805. var gamepad = this.inputs.attached["gamepad"];
  72806. if (gamepad)
  72807. gamepad.gamepadAngularSensibility = value;
  72808. },
  72809. enumerable: true,
  72810. configurable: true
  72811. });
  72812. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72813. get: function () {
  72814. var gamepad = this.inputs.attached["gamepad"];
  72815. if (gamepad)
  72816. return gamepad.gamepadMoveSensibility;
  72817. return 0;
  72818. },
  72819. set: function (value) {
  72820. var gamepad = this.inputs.attached["gamepad"];
  72821. if (gamepad)
  72822. gamepad.gamepadMoveSensibility = value;
  72823. },
  72824. enumerable: true,
  72825. configurable: true
  72826. });
  72827. GamepadCamera.prototype.getClassName = function () {
  72828. return "GamepadCamera";
  72829. };
  72830. return GamepadCamera;
  72831. }(BABYLON.UniversalCamera));
  72832. BABYLON.GamepadCamera = GamepadCamera;
  72833. })(BABYLON || (BABYLON = {}));
  72834. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72835. var BABYLON;
  72836. (function (BABYLON) {
  72837. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72838. function PostProcessRenderPipelineManager() {
  72839. this._renderPipelines = {};
  72840. }
  72841. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72842. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72843. };
  72844. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72845. if (unique === void 0) { unique = false; }
  72846. var renderPipeline = this._renderPipelines[renderPipelineName];
  72847. if (!renderPipeline) {
  72848. return;
  72849. }
  72850. renderPipeline._attachCameras(cameras, unique);
  72851. };
  72852. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72853. var renderPipeline = this._renderPipelines[renderPipelineName];
  72854. if (!renderPipeline) {
  72855. return;
  72856. }
  72857. renderPipeline._detachCameras(cameras);
  72858. };
  72859. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72860. var renderPipeline = this._renderPipelines[renderPipelineName];
  72861. if (!renderPipeline) {
  72862. return;
  72863. }
  72864. renderPipeline._enableEffect(renderEffectName, cameras);
  72865. };
  72866. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72867. var renderPipeline = this._renderPipelines[renderPipelineName];
  72868. if (!renderPipeline) {
  72869. return;
  72870. }
  72871. renderPipeline._disableEffect(renderEffectName, cameras);
  72872. };
  72873. PostProcessRenderPipelineManager.prototype.update = function () {
  72874. for (var renderPipelineName in this._renderPipelines) {
  72875. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72876. var pipeline = this._renderPipelines[renderPipelineName];
  72877. if (!pipeline.isSupported) {
  72878. pipeline.dispose();
  72879. delete this._renderPipelines[renderPipelineName];
  72880. }
  72881. else {
  72882. pipeline._update();
  72883. }
  72884. }
  72885. }
  72886. };
  72887. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72888. for (var renderPipelineName in this._renderPipelines) {
  72889. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72890. var pipeline = this._renderPipelines[renderPipelineName];
  72891. pipeline._rebuild();
  72892. }
  72893. }
  72894. };
  72895. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72896. for (var renderPipelineName in this._renderPipelines) {
  72897. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72898. var pipeline = this._renderPipelines[renderPipelineName];
  72899. pipeline.dispose();
  72900. }
  72901. }
  72902. };
  72903. return PostProcessRenderPipelineManager;
  72904. }());
  72905. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72906. })(BABYLON || (BABYLON = {}));
  72907. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72908. var BABYLON;
  72909. (function (BABYLON) {
  72910. /**
  72911. * This represents a set of one or more post processes in Babylon.
  72912. * A post process can be used to apply a shader to a texture after it is rendered.
  72913. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72914. */
  72915. var PostProcessRenderEffect = /** @class */ (function () {
  72916. /**
  72917. * Instantiates a post process render effect.
  72918. * A post process can be used to apply a shader to a texture after it is rendered.
  72919. * @param engine The engine the effect is tied to
  72920. * @param name The name of the effect
  72921. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72922. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72923. */
  72924. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72925. this._name = name;
  72926. this._singleInstance = singleInstance || true;
  72927. this._getPostProcesses = getPostProcesses;
  72928. this._cameras = {};
  72929. this._indicesForCamera = {};
  72930. this._postProcesses = {};
  72931. }
  72932. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72933. /**
  72934. * Checks if all the post processes in the effect are supported.
  72935. */
  72936. get: function () {
  72937. for (var index in this._postProcesses) {
  72938. if (this._postProcesses.hasOwnProperty(index)) {
  72939. var pps = this._postProcesses[index];
  72940. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72941. if (!pps[ppIndex].isSupported) {
  72942. return false;
  72943. }
  72944. }
  72945. }
  72946. }
  72947. return true;
  72948. },
  72949. enumerable: true,
  72950. configurable: true
  72951. });
  72952. /**
  72953. * Updates the current state of the effect
  72954. */
  72955. PostProcessRenderEffect.prototype._update = function () {
  72956. };
  72957. /**
  72958. * Attaches the effect on cameras
  72959. * @param cameras The camera to attach to.
  72960. */
  72961. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72962. var _this = this;
  72963. var cameraKey;
  72964. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72965. if (!cams) {
  72966. return;
  72967. }
  72968. for (var i = 0; i < cams.length; i++) {
  72969. var camera = cams[i];
  72970. var cameraName = camera.name;
  72971. if (this._singleInstance) {
  72972. cameraKey = 0;
  72973. }
  72974. else {
  72975. cameraKey = cameraName;
  72976. }
  72977. if (!this._postProcesses[cameraKey]) {
  72978. var postProcess = this._getPostProcesses();
  72979. if (postProcess) {
  72980. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72981. }
  72982. }
  72983. if (!this._indicesForCamera[cameraName]) {
  72984. this._indicesForCamera[cameraName] = [];
  72985. }
  72986. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72987. var index = camera.attachPostProcess(postProcess);
  72988. _this._indicesForCamera[cameraName].push(index);
  72989. });
  72990. if (!this._cameras[cameraName]) {
  72991. this._cameras[cameraName] = camera;
  72992. }
  72993. }
  72994. };
  72995. /**
  72996. * Detatches the effect on cameras
  72997. * @param cameras The camera to detatch from.
  72998. */
  72999. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73000. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73001. if (!cams) {
  73002. return;
  73003. }
  73004. for (var i = 0; i < cams.length; i++) {
  73005. var camera = cams[i];
  73006. var cameraName = camera.name;
  73007. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73008. camera.detachPostProcess(postProcess);
  73009. });
  73010. if (this._cameras[cameraName]) {
  73011. //this._indicesForCamera.splice(index, 1);
  73012. this._cameras[cameraName] = null;
  73013. }
  73014. }
  73015. };
  73016. /**
  73017. * Enables the effect on given cameras
  73018. * @param cameras The camera to enable.
  73019. */
  73020. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73021. var _this = this;
  73022. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73023. if (!cams) {
  73024. return;
  73025. }
  73026. for (var i = 0; i < cams.length; i++) {
  73027. var camera = cams[i];
  73028. var cameraName = camera.name;
  73029. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73030. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73031. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73032. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73033. });
  73034. }
  73035. }
  73036. }
  73037. };
  73038. /**
  73039. * Disables the effect on the given cameras
  73040. * @param cameras The camera to disable.
  73041. */
  73042. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73043. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73044. if (!cams) {
  73045. return;
  73046. }
  73047. for (var i = 0; i < cams.length; i++) {
  73048. var camera = cams[i];
  73049. var cameraName = camera.name;
  73050. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73051. camera.detachPostProcess(postProcess);
  73052. });
  73053. }
  73054. };
  73055. /**
  73056. * Gets a list of the post processes contained in the effect.
  73057. * @param camera The camera to get the post processes on.
  73058. * @returns The list of the post processes in the effect.
  73059. */
  73060. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73061. if (this._singleInstance) {
  73062. return this._postProcesses[0];
  73063. }
  73064. else {
  73065. if (!camera) {
  73066. return null;
  73067. }
  73068. return this._postProcesses[camera.name];
  73069. }
  73070. };
  73071. return PostProcessRenderEffect;
  73072. }());
  73073. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73074. })(BABYLON || (BABYLON = {}));
  73075. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73076. var BABYLON;
  73077. (function (BABYLON) {
  73078. var PostProcessRenderPipeline = /** @class */ (function () {
  73079. function PostProcessRenderPipeline(engine, name) {
  73080. this.engine = engine;
  73081. this._name = name;
  73082. this._renderEffects = {};
  73083. this._renderEffectsForIsolatedPass = new Array();
  73084. this._cameras = [];
  73085. }
  73086. PostProcessRenderPipeline.prototype.getClassName = function () {
  73087. return "PostProcessRenderPipeline";
  73088. };
  73089. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73090. get: function () {
  73091. for (var renderEffectName in this._renderEffects) {
  73092. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73093. if (!this._renderEffects[renderEffectName].isSupported) {
  73094. return false;
  73095. }
  73096. }
  73097. }
  73098. return true;
  73099. },
  73100. enumerable: true,
  73101. configurable: true
  73102. });
  73103. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73104. this._renderEffects[renderEffect._name] = renderEffect;
  73105. };
  73106. // private
  73107. PostProcessRenderPipeline.prototype._rebuild = function () {
  73108. };
  73109. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73110. var renderEffects = this._renderEffects[renderEffectName];
  73111. if (!renderEffects) {
  73112. return;
  73113. }
  73114. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73115. };
  73116. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73117. var renderEffects = this._renderEffects[renderEffectName];
  73118. if (!renderEffects) {
  73119. return;
  73120. }
  73121. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73122. };
  73123. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73124. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73125. if (!cams) {
  73126. return;
  73127. }
  73128. var indicesToDelete = [];
  73129. var i;
  73130. for (i = 0; i < cams.length; i++) {
  73131. var camera = cams[i];
  73132. var cameraName = camera.name;
  73133. if (this._cameras.indexOf(camera) === -1) {
  73134. this._cameras[cameraName] = camera;
  73135. }
  73136. else if (unique) {
  73137. indicesToDelete.push(i);
  73138. }
  73139. }
  73140. for (i = 0; i < indicesToDelete.length; i++) {
  73141. cameras.splice(indicesToDelete[i], 1);
  73142. }
  73143. for (var renderEffectName in this._renderEffects) {
  73144. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73145. this._renderEffects[renderEffectName]._attachCameras(cams);
  73146. }
  73147. }
  73148. };
  73149. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73150. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73151. if (!cams) {
  73152. return;
  73153. }
  73154. for (var renderEffectName in this._renderEffects) {
  73155. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73156. this._renderEffects[renderEffectName]._detachCameras(cams);
  73157. }
  73158. }
  73159. for (var i = 0; i < cams.length; i++) {
  73160. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73161. }
  73162. };
  73163. PostProcessRenderPipeline.prototype._update = function () {
  73164. for (var renderEffectName in this._renderEffects) {
  73165. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73166. this._renderEffects[renderEffectName]._update();
  73167. }
  73168. }
  73169. for (var i = 0; i < this._cameras.length; i++) {
  73170. var cameraName = this._cameras[i].name;
  73171. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73172. this._renderEffectsForIsolatedPass[cameraName]._update();
  73173. }
  73174. }
  73175. };
  73176. PostProcessRenderPipeline.prototype._reset = function () {
  73177. this._renderEffects = {};
  73178. this._renderEffectsForIsolatedPass = new Array();
  73179. };
  73180. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73181. // 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)
  73182. var effectKeys = Object.keys(this._renderEffects);
  73183. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73184. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73185. if (postProcesses) {
  73186. postProcesses[0].samples = sampleCount;
  73187. return true;
  73188. }
  73189. }
  73190. return false;
  73191. };
  73192. PostProcessRenderPipeline.prototype.dispose = function () {
  73193. // Must be implemented by children
  73194. };
  73195. __decorate([
  73196. BABYLON.serialize()
  73197. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73198. return PostProcessRenderPipeline;
  73199. }());
  73200. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73201. })(BABYLON || (BABYLON = {}));
  73202. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73203. var BABYLON;
  73204. (function (BABYLON) {
  73205. /**
  73206. * This represents a depth renderer in Babylon.
  73207. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73208. */
  73209. var DepthRenderer = /** @class */ (function () {
  73210. /**
  73211. * Instantiates a depth renderer
  73212. * @param scene The scene the renderer belongs to
  73213. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73214. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73215. */
  73216. function DepthRenderer(scene, type, camera) {
  73217. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73218. if (camera === void 0) { camera = null; }
  73219. var _this = this;
  73220. this._scene = scene;
  73221. this._camera = camera;
  73222. var engine = scene.getEngine();
  73223. // Render target
  73224. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73225. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73226. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73227. this._depthMap.refreshRate = 1;
  73228. this._depthMap.renderParticles = false;
  73229. this._depthMap.renderList = null;
  73230. // Camera to get depth map from to support multiple concurrent cameras
  73231. this._depthMap.activeCamera = this._camera;
  73232. this._depthMap.ignoreCameraViewport = true;
  73233. this._depthMap.useCameraPostProcesses = false;
  73234. // set default depth value to 1.0 (far away)
  73235. this._depthMap.onClearObservable.add(function (engine) {
  73236. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73237. });
  73238. // Custom render function
  73239. var renderSubMesh = function (subMesh) {
  73240. var mesh = subMesh.getRenderingMesh();
  73241. var scene = _this._scene;
  73242. var engine = scene.getEngine();
  73243. var material = subMesh.getMaterial();
  73244. if (!material) {
  73245. return;
  73246. }
  73247. // Culling and reverse (right handed system)
  73248. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73249. // Managing instances
  73250. var batch = mesh._getInstancesRenderList(subMesh._id);
  73251. if (batch.mustReturn) {
  73252. return;
  73253. }
  73254. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73255. var camera = _this._camera || scene.activeCamera;
  73256. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73257. engine.enableEffect(_this._effect);
  73258. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73259. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73260. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73261. // Alpha test
  73262. if (material && material.needAlphaTesting()) {
  73263. var alphaTexture = material.getAlphaTestTexture();
  73264. if (alphaTexture) {
  73265. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73266. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73267. }
  73268. }
  73269. // Bones
  73270. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73271. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73272. }
  73273. // Draw
  73274. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73275. }
  73276. };
  73277. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73278. var index;
  73279. if (depthOnlySubMeshes.length) {
  73280. engine.setColorWrite(false);
  73281. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73282. renderSubMesh(depthOnlySubMeshes.data[index]);
  73283. }
  73284. engine.setColorWrite(true);
  73285. }
  73286. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73287. renderSubMesh(opaqueSubMeshes.data[index]);
  73288. }
  73289. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73290. renderSubMesh(alphaTestSubMeshes.data[index]);
  73291. }
  73292. };
  73293. }
  73294. /**
  73295. * Creates the depth rendering effect and checks if the effect is ready.
  73296. * @param subMesh The submesh to be used to render the depth map of
  73297. * @param useInstances If multiple world instances should be used
  73298. * @returns if the depth renderer is ready to render the depth map
  73299. */
  73300. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73301. var material = subMesh.getMaterial();
  73302. if (material.disableDepthWrite) {
  73303. return false;
  73304. }
  73305. var defines = [];
  73306. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73307. var mesh = subMesh.getMesh();
  73308. // Alpha test
  73309. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73310. defines.push("#define ALPHATEST");
  73311. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73312. attribs.push(BABYLON.VertexBuffer.UVKind);
  73313. defines.push("#define UV1");
  73314. }
  73315. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73316. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73317. defines.push("#define UV2");
  73318. }
  73319. }
  73320. // Bones
  73321. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73322. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73323. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73324. if (mesh.numBoneInfluencers > 4) {
  73325. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73326. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73327. }
  73328. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73329. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73330. }
  73331. else {
  73332. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73333. }
  73334. // Instances
  73335. if (useInstances) {
  73336. defines.push("#define INSTANCES");
  73337. attribs.push("world0");
  73338. attribs.push("world1");
  73339. attribs.push("world2");
  73340. attribs.push("world3");
  73341. }
  73342. // Get correct effect
  73343. var join = defines.join("\n");
  73344. if (this._cachedDefines !== join) {
  73345. this._cachedDefines = join;
  73346. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73347. }
  73348. return this._effect.isReady();
  73349. };
  73350. /**
  73351. * Gets the texture which the depth map will be written to.
  73352. * @returns The depth map texture
  73353. */
  73354. DepthRenderer.prototype.getDepthMap = function () {
  73355. return this._depthMap;
  73356. };
  73357. /**
  73358. * Disposes of the depth renderer.
  73359. */
  73360. DepthRenderer.prototype.dispose = function () {
  73361. this._depthMap.dispose();
  73362. };
  73363. return DepthRenderer;
  73364. }());
  73365. BABYLON.DepthRenderer = DepthRenderer;
  73366. })(BABYLON || (BABYLON = {}));
  73367. //# sourceMappingURL=babylon.depthRenderer.js.map
  73368. var BABYLON;
  73369. (function (BABYLON) {
  73370. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73371. __extends(SSAORenderingPipeline, _super);
  73372. /**
  73373. * @constructor
  73374. * @param {string} name - The rendering pipeline name
  73375. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73376. * @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 }
  73377. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73378. */
  73379. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73380. var _this = _super.call(this, scene.getEngine(), name) || this;
  73381. // Members
  73382. /**
  73383. * The PassPostProcess id in the pipeline that contains the original scene color
  73384. */
  73385. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73386. /**
  73387. * The SSAO PostProcess id in the pipeline
  73388. */
  73389. _this.SSAORenderEffect = "SSAORenderEffect";
  73390. /**
  73391. * The horizontal blur PostProcess id in the pipeline
  73392. */
  73393. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73394. /**
  73395. * The vertical blur PostProcess id in the pipeline
  73396. */
  73397. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73398. /**
  73399. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73400. */
  73401. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73402. /**
  73403. * The output strength of the SSAO post-process. Default value is 1.0.
  73404. */
  73405. _this.totalStrength = 1.0;
  73406. /**
  73407. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73408. */
  73409. _this.radius = 0.0001;
  73410. /**
  73411. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73412. * Must not be equal to fallOff and superior to fallOff.
  73413. * Default value is 0.975
  73414. */
  73415. _this.area = 0.0075;
  73416. /**
  73417. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73418. * Must not be equal to area and inferior to area.
  73419. * Default value is 0.0
  73420. */
  73421. _this.fallOff = 0.000001;
  73422. /**
  73423. * The base color of the SSAO post-process
  73424. * The final result is "base + ssao" between [0, 1]
  73425. */
  73426. _this.base = 0.5;
  73427. _this._firstUpdate = true;
  73428. _this._scene = scene;
  73429. // Set up assets
  73430. _this._createRandomTexture();
  73431. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73432. var ssaoRatio = ratio.ssaoRatio || ratio;
  73433. var combineRatio = ratio.combineRatio || ratio;
  73434. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73435. _this._createSSAOPostProcess(ssaoRatio);
  73436. _this._createBlurPostProcess(ssaoRatio);
  73437. _this._createSSAOCombinePostProcess(combineRatio);
  73438. // Set up pipeline
  73439. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73440. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73441. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73442. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73443. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73444. // Finish
  73445. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73446. if (cameras)
  73447. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73448. return _this;
  73449. }
  73450. // Public Methods
  73451. /**
  73452. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73453. */
  73454. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73455. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73456. for (var i = 0; i < this._scene.cameras.length; i++) {
  73457. var camera = this._scene.cameras[i];
  73458. this._originalColorPostProcess.dispose(camera);
  73459. this._ssaoPostProcess.dispose(camera);
  73460. this._blurHPostProcess.dispose(camera);
  73461. this._blurVPostProcess.dispose(camera);
  73462. this._ssaoCombinePostProcess.dispose(camera);
  73463. }
  73464. this._randomTexture.dispose();
  73465. if (disableDepthRender)
  73466. this._scene.disableDepthRenderer();
  73467. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73468. _super.prototype.dispose.call(this);
  73469. };
  73470. // Private Methods
  73471. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73472. var _this = this;
  73473. var size = 16;
  73474. 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);
  73475. 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);
  73476. this._blurHPostProcess.onActivateObservable.add(function () {
  73477. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73478. _this._blurHPostProcess.kernel = size * dw;
  73479. });
  73480. this._blurVPostProcess.onActivateObservable.add(function () {
  73481. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73482. _this._blurVPostProcess.kernel = size * dw;
  73483. });
  73484. };
  73485. SSAORenderingPipeline.prototype._rebuild = function () {
  73486. this._firstUpdate = true;
  73487. _super.prototype._rebuild.call(this);
  73488. };
  73489. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73490. var _this = this;
  73491. var numSamples = 16;
  73492. var sampleSphere = [
  73493. 0.5381, 0.1856, -0.4319,
  73494. 0.1379, 0.2486, 0.4430,
  73495. 0.3371, 0.5679, -0.0057,
  73496. -0.6999, -0.0451, -0.0019,
  73497. 0.0689, -0.1598, -0.8547,
  73498. 0.0560, 0.0069, -0.1843,
  73499. -0.0146, 0.1402, 0.0762,
  73500. 0.0100, -0.1924, -0.0344,
  73501. -0.3577, -0.5301, -0.4358,
  73502. -0.3169, 0.1063, 0.0158,
  73503. 0.0103, -0.5869, 0.0046,
  73504. -0.0897, -0.4940, 0.3287,
  73505. 0.7119, -0.0154, -0.0918,
  73506. -0.0533, 0.0596, -0.5411,
  73507. 0.0352, -0.0631, 0.5460,
  73508. -0.4776, 0.2847, -0.0271
  73509. ];
  73510. var samplesFactor = 1.0 / numSamples;
  73511. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73512. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73513. "area", "fallOff", "base", "range", "viewport"
  73514. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73515. this._ssaoPostProcess.onApply = function (effect) {
  73516. if (_this._firstUpdate) {
  73517. effect.setArray3("sampleSphere", sampleSphere);
  73518. effect.setFloat("samplesFactor", samplesFactor);
  73519. effect.setFloat("randTextureTiles", 4.0);
  73520. }
  73521. effect.setFloat("totalStrength", _this.totalStrength);
  73522. effect.setFloat("radius", _this.radius);
  73523. effect.setFloat("area", _this.area);
  73524. effect.setFloat("fallOff", _this.fallOff);
  73525. effect.setFloat("base", _this.base);
  73526. effect.setTexture("textureSampler", _this._depthTexture);
  73527. effect.setTexture("randomSampler", _this._randomTexture);
  73528. };
  73529. };
  73530. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73531. var _this = this;
  73532. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73533. this._ssaoCombinePostProcess.onApply = function (effect) {
  73534. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73535. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73536. };
  73537. };
  73538. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73539. var size = 512;
  73540. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73541. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73542. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73543. var context = this._randomTexture.getContext();
  73544. var rand = function (min, max) {
  73545. return Math.random() * (max - min) + min;
  73546. };
  73547. var randVector = BABYLON.Vector3.Zero();
  73548. for (var x = 0; x < size; x++) {
  73549. for (var y = 0; y < size; y++) {
  73550. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73551. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73552. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73553. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73554. context.fillRect(x, y, 1, 1);
  73555. }
  73556. }
  73557. this._randomTexture.update(false);
  73558. };
  73559. __decorate([
  73560. BABYLON.serialize()
  73561. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73562. __decorate([
  73563. BABYLON.serialize()
  73564. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73565. __decorate([
  73566. BABYLON.serialize()
  73567. ], SSAORenderingPipeline.prototype, "area", void 0);
  73568. __decorate([
  73569. BABYLON.serialize()
  73570. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73571. __decorate([
  73572. BABYLON.serialize()
  73573. ], SSAORenderingPipeline.prototype, "base", void 0);
  73574. return SSAORenderingPipeline;
  73575. }(BABYLON.PostProcessRenderPipeline));
  73576. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73577. })(BABYLON || (BABYLON = {}));
  73578. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73579. var BABYLON;
  73580. (function (BABYLON) {
  73581. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73582. __extends(SSAO2RenderingPipeline, _super);
  73583. /**
  73584. * @constructor
  73585. * @param {string} name - The rendering pipeline name
  73586. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73587. * @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 }
  73588. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73589. */
  73590. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73591. var _this = _super.call(this, scene.getEngine(), name) || this;
  73592. // Members
  73593. /**
  73594. * The PassPostProcess id in the pipeline that contains the original scene color
  73595. */
  73596. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73597. /**
  73598. * The SSAO PostProcess id in the pipeline
  73599. */
  73600. _this.SSAORenderEffect = "SSAORenderEffect";
  73601. /**
  73602. * The horizontal blur PostProcess id in the pipeline
  73603. */
  73604. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73605. /**
  73606. * The vertical blur PostProcess id in the pipeline
  73607. */
  73608. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73609. /**
  73610. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73611. */
  73612. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73613. /**
  73614. * The output strength of the SSAO post-process. Default value is 1.0.
  73615. */
  73616. _this.totalStrength = 1.0;
  73617. /**
  73618. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73619. */
  73620. _this.maxZ = 100.0;
  73621. /**
  73622. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73623. */
  73624. _this.minZAspect = 0.2;
  73625. /**
  73626. * Number of samples used for the SSAO calculations. Default value is 8
  73627. */
  73628. _this._samples = 8;
  73629. /**
  73630. * Are we using bilateral blur ?
  73631. */
  73632. _this._expensiveBlur = true;
  73633. /**
  73634. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73635. */
  73636. _this.radius = 2.0;
  73637. /**
  73638. * The base color of the SSAO post-process
  73639. * The final result is "base + ssao" between [0, 1]
  73640. */
  73641. _this.base = 0.1;
  73642. _this._firstUpdate = true;
  73643. _this._scene = scene;
  73644. _this._ratio = ratio;
  73645. if (!_this.isSupported) {
  73646. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73647. return _this;
  73648. }
  73649. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73650. var blurRatio = _this._ratio.blurRatio || ratio;
  73651. // Set up assets
  73652. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73653. _this._createRandomTexture();
  73654. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73655. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73656. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73657. _this._createSSAOPostProcess(1.0);
  73658. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73659. _this._createSSAOCombinePostProcess(blurRatio);
  73660. // Set up pipeline
  73661. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73662. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73663. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73664. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73665. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73666. // Finish
  73667. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73668. if (cameras)
  73669. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73670. return _this;
  73671. }
  73672. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73673. get: function () {
  73674. return this._samples;
  73675. },
  73676. set: function (n) {
  73677. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73678. this._samples = n;
  73679. this._sampleSphere = this._generateHemisphere();
  73680. this._firstUpdate = true;
  73681. },
  73682. enumerable: true,
  73683. configurable: true
  73684. });
  73685. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73686. get: function () {
  73687. return this._expensiveBlur;
  73688. },
  73689. set: function (b) {
  73690. 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"]);
  73691. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73692. this._expensiveBlur = b;
  73693. this._firstUpdate = true;
  73694. },
  73695. enumerable: true,
  73696. configurable: true
  73697. });
  73698. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73699. /**
  73700. * Support test.
  73701. */
  73702. get: function () {
  73703. var engine = BABYLON.Engine.LastCreatedEngine;
  73704. if (!engine) {
  73705. return false;
  73706. }
  73707. return engine.getCaps().drawBuffersExtension;
  73708. },
  73709. enumerable: true,
  73710. configurable: true
  73711. });
  73712. // Public Methods
  73713. /**
  73714. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73715. */
  73716. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73717. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73718. for (var i = 0; i < this._scene.cameras.length; i++) {
  73719. var camera = this._scene.cameras[i];
  73720. this._originalColorPostProcess.dispose(camera);
  73721. this._ssaoPostProcess.dispose(camera);
  73722. this._blurHPostProcess.dispose(camera);
  73723. this._blurVPostProcess.dispose(camera);
  73724. this._ssaoCombinePostProcess.dispose(camera);
  73725. }
  73726. this._randomTexture.dispose();
  73727. if (disableGeometryBufferRenderer)
  73728. this._scene.disableGeometryBufferRenderer();
  73729. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73730. _super.prototype.dispose.call(this);
  73731. };
  73732. // Private Methods
  73733. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73734. var _this = this;
  73735. this._samplerOffsets = [];
  73736. var expensive = this.expensiveBlur;
  73737. for (var i = -8; i < 8; i++) {
  73738. this._samplerOffsets.push(i * 2 + 0.5);
  73739. }
  73740. 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");
  73741. this._blurHPostProcess.onApply = function (effect) {
  73742. if (!_this._scene.activeCamera) {
  73743. return;
  73744. }
  73745. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73746. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73747. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73748. effect.setFloat("radius", _this.radius);
  73749. effect.setTexture("depthSampler", _this._depthTexture);
  73750. if (_this._firstUpdate) {
  73751. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73752. }
  73753. };
  73754. 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");
  73755. this._blurVPostProcess.onApply = function (effect) {
  73756. if (!_this._scene.activeCamera) {
  73757. return;
  73758. }
  73759. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73760. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73761. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73762. effect.setFloat("radius", _this.radius);
  73763. effect.setTexture("depthSampler", _this._depthTexture);
  73764. if (_this._firstUpdate) {
  73765. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73766. _this._firstUpdate = false;
  73767. }
  73768. };
  73769. };
  73770. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73771. this._firstUpdate = true;
  73772. _super.prototype._rebuild.call(this);
  73773. };
  73774. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73775. var numSamples = this.samples;
  73776. var result = [];
  73777. var vector, scale;
  73778. var rand = function (min, max) {
  73779. return Math.random() * (max - min) + min;
  73780. };
  73781. var i = 0;
  73782. while (i < numSamples) {
  73783. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73784. vector.normalize();
  73785. scale = i / numSamples;
  73786. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73787. vector.scaleInPlace(scale);
  73788. result.push(vector.x, vector.y, vector.z);
  73789. i++;
  73790. }
  73791. return result;
  73792. };
  73793. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73794. var _this = this;
  73795. var numSamples = this.samples;
  73796. this._sampleSphere = this._generateHemisphere();
  73797. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73798. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73799. "base", "range", "projection", "near", "far", "texelSize",
  73800. "xViewport", "yViewport", "maxZ", "minZAspect"
  73801. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73802. this._ssaoPostProcess.onApply = function (effect) {
  73803. if (_this._firstUpdate) {
  73804. effect.setArray3("sampleSphere", _this._sampleSphere);
  73805. effect.setFloat("randTextureTiles", 4.0);
  73806. }
  73807. if (!_this._scene.activeCamera) {
  73808. return;
  73809. }
  73810. effect.setFloat("samplesFactor", 1 / _this.samples);
  73811. effect.setFloat("totalStrength", _this.totalStrength);
  73812. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73813. effect.setFloat("radius", _this.radius);
  73814. effect.setFloat("maxZ", _this.maxZ);
  73815. effect.setFloat("minZAspect", _this.minZAspect);
  73816. effect.setFloat("base", _this.base);
  73817. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73818. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73819. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73820. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73821. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73822. effect.setTexture("textureSampler", _this._depthTexture);
  73823. effect.setTexture("normalSampler", _this._normalTexture);
  73824. effect.setTexture("randomSampler", _this._randomTexture);
  73825. };
  73826. };
  73827. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73828. var _this = this;
  73829. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73830. this._ssaoCombinePostProcess.onApply = function (effect) {
  73831. var viewport = _this._scene.activeCamera.viewport;
  73832. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73833. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73834. };
  73835. };
  73836. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73837. var size = 512;
  73838. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73839. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73840. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73841. var context = this._randomTexture.getContext();
  73842. var rand = function (min, max) {
  73843. return Math.random() * (max - min) + min;
  73844. };
  73845. var randVector = BABYLON.Vector3.Zero();
  73846. for (var x = 0; x < size; x++) {
  73847. for (var y = 0; y < size; y++) {
  73848. randVector.x = rand(0.0, 1.0);
  73849. randVector.y = rand(0.0, 1.0);
  73850. randVector.z = 0.0;
  73851. randVector.normalize();
  73852. randVector.scaleInPlace(255);
  73853. randVector.x = Math.floor(randVector.x);
  73854. randVector.y = Math.floor(randVector.y);
  73855. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73856. context.fillRect(x, y, 1, 1);
  73857. }
  73858. }
  73859. this._randomTexture.update(false);
  73860. };
  73861. /**
  73862. * Serialize the rendering pipeline (Used when exporting)
  73863. * @returns the serialized object
  73864. */
  73865. SSAO2RenderingPipeline.prototype.serialize = function () {
  73866. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73867. serializationObject.customType = "SSAO2RenderingPipeline";
  73868. return serializationObject;
  73869. };
  73870. /**
  73871. * Parse the serialized pipeline
  73872. * @param source Source pipeline.
  73873. * @param scene The scene to load the pipeline to.
  73874. * @param rootUrl The URL of the serialized pipeline.
  73875. * @returns An instantiated pipeline from the serialized object.
  73876. */
  73877. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73878. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73879. };
  73880. __decorate([
  73881. BABYLON.serialize()
  73882. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73883. __decorate([
  73884. BABYLON.serialize()
  73885. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73886. __decorate([
  73887. BABYLON.serialize()
  73888. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73889. __decorate([
  73890. BABYLON.serialize("samples")
  73891. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73892. __decorate([
  73893. BABYLON.serialize()
  73894. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73895. __decorate([
  73896. BABYLON.serialize("expensiveBlur")
  73897. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73898. __decorate([
  73899. BABYLON.serialize()
  73900. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73901. __decorate([
  73902. BABYLON.serialize()
  73903. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73904. return SSAO2RenderingPipeline;
  73905. }(BABYLON.PostProcessRenderPipeline));
  73906. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73907. })(BABYLON || (BABYLON = {}));
  73908. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73909. // BABYLON.JS Chromatic Aberration GLSL Shader
  73910. // Author: Olivier Guyot
  73911. // Separates very slightly R, G and B colors on the edges of the screen
  73912. // Inspired by Francois Tarlier & Martins Upitis
  73913. var BABYLON;
  73914. (function (BABYLON) {
  73915. var LensRenderingPipeline = /** @class */ (function (_super) {
  73916. __extends(LensRenderingPipeline, _super);
  73917. /**
  73918. * @constructor
  73919. *
  73920. * Effect parameters are as follow:
  73921. * {
  73922. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73923. * edge_blur: number; // from 0 to x (1 for realism)
  73924. * distortion: number; // from 0 to x (1 for realism)
  73925. * grain_amount: number; // from 0 to 1
  73926. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73927. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73928. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73929. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73930. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73931. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73932. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73933. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73934. * }
  73935. * Note: if an effect parameter is unset, effect is disabled
  73936. *
  73937. * @param {string} name - The rendering pipeline name
  73938. * @param {object} parameters - An object containing all parameters (see above)
  73939. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73940. * @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)
  73941. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73942. */
  73943. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73944. if (ratio === void 0) { ratio = 1.0; }
  73945. var _this = _super.call(this, scene.getEngine(), name) || this;
  73946. // Lens effects can be of the following:
  73947. // - chromatic aberration (slight shift of RGB colors)
  73948. // - blur on the edge of the lens
  73949. // - lens distortion
  73950. // - depth-of-field blur & highlights enhancing
  73951. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73952. // - grain effect (noise or custom texture)
  73953. // Two additional texture samplers are needed:
  73954. // - depth map (for depth-of-field)
  73955. // - grain texture
  73956. /**
  73957. * The chromatic aberration PostProcess id in the pipeline
  73958. */
  73959. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73960. /**
  73961. * The highlights enhancing PostProcess id in the pipeline
  73962. */
  73963. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73964. /**
  73965. * The depth-of-field PostProcess id in the pipeline
  73966. */
  73967. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73968. _this._scene = scene;
  73969. // Fetch texture samplers
  73970. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73971. if (parameters.grain_texture) {
  73972. _this._grainTexture = parameters.grain_texture;
  73973. }
  73974. else {
  73975. _this._createGrainTexture();
  73976. }
  73977. // save parameters
  73978. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73979. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73980. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73981. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73982. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73983. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73984. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73985. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73986. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73987. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73988. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73989. // Create effects
  73990. _this._createChromaticAberrationPostProcess(ratio);
  73991. _this._createHighlightsPostProcess(ratio);
  73992. _this._createDepthOfFieldPostProcess(ratio / 4);
  73993. // Set up pipeline
  73994. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73995. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73996. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73997. if (_this._highlightsGain === -1) {
  73998. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73999. }
  74000. // Finish
  74001. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74002. if (cameras) {
  74003. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74004. }
  74005. return _this;
  74006. }
  74007. // public methods (self explanatory)
  74008. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74009. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74010. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74011. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74012. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74013. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74014. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74015. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74016. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74017. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74018. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74019. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74020. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74021. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74022. };
  74023. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74024. this._highlightsPostProcess.updateEffect();
  74025. };
  74026. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74027. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74028. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74029. this._highlightsGain = amount;
  74030. };
  74031. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74032. if (this._highlightsGain === -1) {
  74033. this._highlightsGain = 1.0;
  74034. }
  74035. this._highlightsThreshold = amount;
  74036. };
  74037. LensRenderingPipeline.prototype.disableHighlights = function () {
  74038. this._highlightsGain = -1;
  74039. };
  74040. /**
  74041. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74042. */
  74043. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74044. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74045. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74046. this._chromaticAberrationPostProcess = null;
  74047. this._highlightsPostProcess = null;
  74048. this._depthOfFieldPostProcess = null;
  74049. this._grainTexture.dispose();
  74050. if (disableDepthRender)
  74051. this._scene.disableDepthRenderer();
  74052. };
  74053. // colors shifting and distortion
  74054. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74055. var _this = this;
  74056. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74057. [], // samplers
  74058. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74059. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74060. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74061. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74062. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74063. effect.setFloat('radialIntensity', 1);
  74064. effect.setFloat2('direction', 17, 17);
  74065. effect.setFloat2('centerPosition', 0.5, 0.5);
  74066. };
  74067. };
  74068. // highlights enhancing
  74069. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74070. var _this = this;
  74071. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74072. [], // samplers
  74073. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74074. this._highlightsPostProcess.onApply = function (effect) {
  74075. effect.setFloat('gain', _this._highlightsGain);
  74076. effect.setFloat('threshold', _this._highlightsThreshold);
  74077. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74078. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74079. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74080. };
  74081. };
  74082. // colors shifting and distortion
  74083. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74084. var _this = this;
  74085. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74086. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74087. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74088. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74089. this._depthOfFieldPostProcess.onApply = function (effect) {
  74090. effect.setTexture("depthSampler", _this._depthTexture);
  74091. effect.setTexture("grainSampler", _this._grainTexture);
  74092. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74093. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74094. effect.setFloat('grain_amount', _this._grainAmount);
  74095. effect.setBool('blur_noise', _this._blurNoise);
  74096. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74097. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74098. effect.setFloat('distortion', _this._distortion);
  74099. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74100. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74101. effect.setFloat('aperture', _this._dofAperture);
  74102. effect.setFloat('darken', _this._dofDarken);
  74103. effect.setFloat('edge_blur', _this._edgeBlur);
  74104. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74105. if (_this._scene.activeCamera) {
  74106. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74107. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74108. }
  74109. };
  74110. };
  74111. // creates a black and white random noise texture, 512x512
  74112. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74113. var size = 512;
  74114. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74115. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74116. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74117. var context = this._grainTexture.getContext();
  74118. var rand = function (min, max) {
  74119. return Math.random() * (max - min) + min;
  74120. };
  74121. var value;
  74122. for (var x = 0; x < size; x++) {
  74123. for (var y = 0; y < size; y++) {
  74124. value = Math.floor(rand(0.42, 0.58) * 255);
  74125. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74126. context.fillRect(x, y, 1, 1);
  74127. }
  74128. }
  74129. this._grainTexture.update(false);
  74130. };
  74131. return LensRenderingPipeline;
  74132. }(BABYLON.PostProcessRenderPipeline));
  74133. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74134. })(BABYLON || (BABYLON = {}));
  74135. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74136. var BABYLON;
  74137. (function (BABYLON) {
  74138. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74139. __extends(StandardRenderingPipeline, _super);
  74140. /**
  74141. * @constructor
  74142. * @param {string} name - The rendering pipeline name
  74143. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74144. * @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)
  74145. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74146. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74147. */
  74148. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74149. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74150. var _this = _super.call(this, scene.getEngine(), name) || this;
  74151. _this.downSampleX4PostProcess = null;
  74152. _this.brightPassPostProcess = null;
  74153. _this.blurHPostProcesses = [];
  74154. _this.blurVPostProcesses = [];
  74155. _this.textureAdderPostProcess = null;
  74156. _this.volumetricLightPostProcess = null;
  74157. _this.volumetricLightSmoothXPostProcess = null;
  74158. _this.volumetricLightSmoothYPostProcess = null;
  74159. _this.volumetricLightMergePostProces = null;
  74160. _this.volumetricLightFinalPostProcess = null;
  74161. _this.luminancePostProcess = null;
  74162. _this.luminanceDownSamplePostProcesses = [];
  74163. _this.hdrPostProcess = null;
  74164. _this.textureAdderFinalPostProcess = null;
  74165. _this.lensFlareFinalPostProcess = null;
  74166. _this.hdrFinalPostProcess = null;
  74167. _this.lensFlarePostProcess = null;
  74168. _this.lensFlareComposePostProcess = null;
  74169. _this.motionBlurPostProcess = null;
  74170. _this.depthOfFieldPostProcess = null;
  74171. // Values
  74172. _this.brightThreshold = 1.0;
  74173. _this.blurWidth = 512.0;
  74174. _this.horizontalBlur = false;
  74175. _this.exposure = 1.0;
  74176. _this.lensTexture = null;
  74177. _this.volumetricLightCoefficient = 0.2;
  74178. _this.volumetricLightPower = 4.0;
  74179. _this.volumetricLightBlurScale = 64.0;
  74180. _this.sourceLight = null;
  74181. _this.hdrMinimumLuminance = 1.0;
  74182. _this.hdrDecreaseRate = 0.5;
  74183. _this.hdrIncreaseRate = 0.5;
  74184. _this.lensColorTexture = null;
  74185. _this.lensFlareStrength = 20.0;
  74186. _this.lensFlareGhostDispersal = 1.4;
  74187. _this.lensFlareHaloWidth = 0.7;
  74188. _this.lensFlareDistortionStrength = 16.0;
  74189. _this.lensStarTexture = null;
  74190. _this.lensFlareDirtTexture = null;
  74191. _this.depthOfFieldDistance = 10.0;
  74192. _this.depthOfFieldBlurWidth = 64.0;
  74193. _this.motionStrength = 1.0;
  74194. // IAnimatable
  74195. _this.animations = [];
  74196. _this._currentDepthOfFieldSource = null;
  74197. _this._hdrCurrentLuminance = 1.0;
  74198. // Getters and setters
  74199. _this._bloomEnabled = true;
  74200. _this._depthOfFieldEnabled = false;
  74201. _this._vlsEnabled = false;
  74202. _this._lensFlareEnabled = false;
  74203. _this._hdrEnabled = false;
  74204. _this._motionBlurEnabled = false;
  74205. _this._motionBlurSamples = 64.0;
  74206. _this._volumetricLightStepsCount = 50.0;
  74207. _this._cameras = cameras || [];
  74208. // Initialize
  74209. _this._scene = scene;
  74210. _this._basePostProcess = originalPostProcess;
  74211. _this._ratio = ratio;
  74212. // Misc
  74213. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74214. // Finish
  74215. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74216. _this._buildPipeline();
  74217. return _this;
  74218. }
  74219. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74220. get: function () {
  74221. return this._bloomEnabled;
  74222. },
  74223. set: function (enabled) {
  74224. if (this._bloomEnabled === enabled) {
  74225. return;
  74226. }
  74227. this._bloomEnabled = enabled;
  74228. this._buildPipeline();
  74229. },
  74230. enumerable: true,
  74231. configurable: true
  74232. });
  74233. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74234. get: function () {
  74235. return this._depthOfFieldEnabled;
  74236. },
  74237. set: function (enabled) {
  74238. if (this._depthOfFieldEnabled === enabled) {
  74239. return;
  74240. }
  74241. this._depthOfFieldEnabled = enabled;
  74242. this._buildPipeline();
  74243. },
  74244. enumerable: true,
  74245. configurable: true
  74246. });
  74247. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74248. get: function () {
  74249. return this._lensFlareEnabled;
  74250. },
  74251. set: function (enabled) {
  74252. if (this._lensFlareEnabled === enabled) {
  74253. return;
  74254. }
  74255. this._lensFlareEnabled = enabled;
  74256. this._buildPipeline();
  74257. },
  74258. enumerable: true,
  74259. configurable: true
  74260. });
  74261. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74262. get: function () {
  74263. return this._hdrEnabled;
  74264. },
  74265. set: function (enabled) {
  74266. if (this._hdrEnabled === enabled) {
  74267. return;
  74268. }
  74269. this._hdrEnabled = enabled;
  74270. this._buildPipeline();
  74271. },
  74272. enumerable: true,
  74273. configurable: true
  74274. });
  74275. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74276. get: function () {
  74277. return this._vlsEnabled;
  74278. },
  74279. set: function (enabled) {
  74280. if (this._vlsEnabled === enabled) {
  74281. return;
  74282. }
  74283. if (enabled) {
  74284. var geometry = this._scene.enableGeometryBufferRenderer();
  74285. if (!geometry) {
  74286. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74287. return;
  74288. }
  74289. }
  74290. this._vlsEnabled = enabled;
  74291. this._buildPipeline();
  74292. },
  74293. enumerable: true,
  74294. configurable: true
  74295. });
  74296. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74297. get: function () {
  74298. return this._motionBlurEnabled;
  74299. },
  74300. set: function (enabled) {
  74301. if (this._motionBlurEnabled === enabled) {
  74302. return;
  74303. }
  74304. this._motionBlurEnabled = enabled;
  74305. this._buildPipeline();
  74306. },
  74307. enumerable: true,
  74308. configurable: true
  74309. });
  74310. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74311. get: function () {
  74312. return this._volumetricLightStepsCount;
  74313. },
  74314. set: function (count) {
  74315. if (this.volumetricLightPostProcess) {
  74316. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74317. }
  74318. this._volumetricLightStepsCount = count;
  74319. },
  74320. enumerable: true,
  74321. configurable: true
  74322. });
  74323. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74324. get: function () {
  74325. return this._motionBlurSamples;
  74326. },
  74327. set: function (samples) {
  74328. if (this.motionBlurPostProcess) {
  74329. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74330. }
  74331. this._motionBlurSamples = samples;
  74332. },
  74333. enumerable: true,
  74334. configurable: true
  74335. });
  74336. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74337. var _this = this;
  74338. var ratio = this._ratio;
  74339. var scene = this._scene;
  74340. this._disposePostProcesses();
  74341. this._reset();
  74342. // Create pass post-process
  74343. if (!this._basePostProcess) {
  74344. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74345. this.originalPostProcess.onApply = function (effect) {
  74346. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74347. };
  74348. }
  74349. else {
  74350. this.originalPostProcess = this._basePostProcess;
  74351. }
  74352. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74353. this._currentDepthOfFieldSource = this.originalPostProcess;
  74354. if (this._bloomEnabled) {
  74355. // Create down sample X4 post-process
  74356. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74357. // Create bright pass post-process
  74358. this._createBrightPassPostProcess(scene, ratio / 2);
  74359. // Create gaussian blur post-processes (down sampling blurs)
  74360. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74361. // Create texture adder post-process
  74362. this._createTextureAdderPostProcess(scene, ratio);
  74363. // Create depth-of-field source post-process
  74364. 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);
  74365. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74366. }
  74367. if (this._vlsEnabled) {
  74368. // Create volumetric light
  74369. this._createVolumetricLightPostProcess(scene, ratio);
  74370. // Create volumetric light final post-process
  74371. 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);
  74372. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74373. }
  74374. if (this._lensFlareEnabled) {
  74375. // Create lens flare post-process
  74376. this._createLensFlarePostProcess(scene, ratio);
  74377. // Create depth-of-field source post-process post lens-flare and disable it now
  74378. 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);
  74379. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74380. }
  74381. if (this._hdrEnabled) {
  74382. // Create luminance
  74383. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74384. // Create HDR
  74385. this._createHdrPostProcess(scene, ratio);
  74386. // Create depth-of-field source post-process post hdr and disable it now
  74387. 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);
  74388. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74389. }
  74390. if (this._depthOfFieldEnabled) {
  74391. // Create gaussian blur used by depth-of-field
  74392. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74393. // Create depth-of-field post-process
  74394. this._createDepthOfFieldPostProcess(scene, ratio);
  74395. }
  74396. if (this._motionBlurEnabled) {
  74397. // Create motion blur post-process
  74398. this._createMotionBlurPostProcess(scene, ratio);
  74399. }
  74400. if (this._cameras !== null) {
  74401. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74402. }
  74403. };
  74404. // Down Sample X4 Post-Processs
  74405. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74406. var _this = this;
  74407. var downSampleX4Offsets = new Array(32);
  74408. 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);
  74409. this.downSampleX4PostProcess.onApply = function (effect) {
  74410. var id = 0;
  74411. var width = _this.downSampleX4PostProcess.width;
  74412. var height = _this.downSampleX4PostProcess.height;
  74413. for (var i = -2; i < 2; i++) {
  74414. for (var j = -2; j < 2; j++) {
  74415. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74416. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74417. id += 2;
  74418. }
  74419. }
  74420. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74421. };
  74422. // Add to pipeline
  74423. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74424. };
  74425. // Brightpass Post-Process
  74426. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74427. var _this = this;
  74428. var brightOffsets = new Array(8);
  74429. 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);
  74430. this.brightPassPostProcess.onApply = function (effect) {
  74431. var sU = (1.0 / _this.brightPassPostProcess.width);
  74432. var sV = (1.0 / _this.brightPassPostProcess.height);
  74433. brightOffsets[0] = -0.5 * sU;
  74434. brightOffsets[1] = 0.5 * sV;
  74435. brightOffsets[2] = 0.5 * sU;
  74436. brightOffsets[3] = 0.5 * sV;
  74437. brightOffsets[4] = -0.5 * sU;
  74438. brightOffsets[5] = -0.5 * sV;
  74439. brightOffsets[6] = 0.5 * sU;
  74440. brightOffsets[7] = -0.5 * sV;
  74441. effect.setArray2("dsOffsets", brightOffsets);
  74442. effect.setFloat("brightThreshold", _this.brightThreshold);
  74443. };
  74444. // Add to pipeline
  74445. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74446. };
  74447. // Create blur H&V post-processes
  74448. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74449. var _this = this;
  74450. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74451. var engine = scene.getEngine();
  74452. 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);
  74453. 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);
  74454. blurX.onActivateObservable.add(function () {
  74455. var dw = blurX.width / engine.getRenderWidth();
  74456. blurX.kernel = _this[blurWidthKey] * dw;
  74457. });
  74458. blurY.onActivateObservable.add(function () {
  74459. var dw = blurY.height / engine.getRenderHeight();
  74460. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74461. });
  74462. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74463. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74464. this.blurHPostProcesses.push(blurX);
  74465. this.blurVPostProcesses.push(blurY);
  74466. };
  74467. // Create texture adder post-process
  74468. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74469. var _this = this;
  74470. 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);
  74471. this.textureAdderPostProcess.onApply = function (effect) {
  74472. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74473. effect.setTexture("lensSampler", _this.lensTexture);
  74474. effect.setFloat("exposure", _this.exposure);
  74475. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74476. };
  74477. // Add to pipeline
  74478. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74479. };
  74480. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74481. var _this = this;
  74482. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74483. geometryRenderer.enablePosition = true;
  74484. var geometry = geometryRenderer.getGBuffer();
  74485. // Base post-process
  74486. 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));
  74487. var depthValues = BABYLON.Vector2.Zero();
  74488. this.volumetricLightPostProcess.onApply = function (effect) {
  74489. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74490. var generator = _this.sourceLight.getShadowGenerator();
  74491. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74492. effect.setTexture("positionSampler", geometry.textures[2]);
  74493. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74494. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74495. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74496. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74497. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74498. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74499. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74500. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74501. effect.setVector2("depthValues", depthValues);
  74502. }
  74503. };
  74504. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74505. // Smooth
  74506. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74507. // Merge
  74508. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74509. this.volumetricLightMergePostProces.onApply = function (effect) {
  74510. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74511. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74512. };
  74513. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74514. };
  74515. // Create luminance
  74516. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74517. var _this = this;
  74518. // Create luminance
  74519. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74520. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74521. var offsets = [];
  74522. this.luminancePostProcess.onApply = function (effect) {
  74523. var sU = (1.0 / _this.luminancePostProcess.width);
  74524. var sV = (1.0 / _this.luminancePostProcess.height);
  74525. offsets[0] = -0.5 * sU;
  74526. offsets[1] = 0.5 * sV;
  74527. offsets[2] = 0.5 * sU;
  74528. offsets[3] = 0.5 * sV;
  74529. offsets[4] = -0.5 * sU;
  74530. offsets[5] = -0.5 * sV;
  74531. offsets[6] = 0.5 * sU;
  74532. offsets[7] = -0.5 * sV;
  74533. effect.setArray2("lumOffsets", offsets);
  74534. };
  74535. // Add to pipeline
  74536. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74537. // Create down sample luminance
  74538. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74539. var size = Math.pow(3, i);
  74540. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74541. if (i === 0) {
  74542. defines += "#define FINAL_DOWN_SAMPLER";
  74543. }
  74544. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74545. this.luminanceDownSamplePostProcesses.push(postProcess);
  74546. }
  74547. // Create callbacks and add effects
  74548. var lastLuminance = this.luminancePostProcess;
  74549. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74550. var downSampleOffsets = new Array(18);
  74551. pp.onApply = function (effect) {
  74552. if (!lastLuminance) {
  74553. return;
  74554. }
  74555. var id = 0;
  74556. for (var x = -1; x < 2; x++) {
  74557. for (var y = -1; y < 2; y++) {
  74558. downSampleOffsets[id] = x / lastLuminance.width;
  74559. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74560. id += 2;
  74561. }
  74562. }
  74563. effect.setArray2("dsOffsets", downSampleOffsets);
  74564. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74565. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74566. lastLuminance = _this.luminancePostProcess;
  74567. }
  74568. else {
  74569. lastLuminance = pp;
  74570. }
  74571. };
  74572. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74573. pp.onAfterRender = function (effect) {
  74574. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74575. 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);
  74576. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74577. };
  74578. }
  74579. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74580. });
  74581. };
  74582. // Create HDR post-process
  74583. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74584. var _this = this;
  74585. 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);
  74586. var outputLiminance = 1;
  74587. var time = 0;
  74588. var lastTime = 0;
  74589. this.hdrPostProcess.onApply = function (effect) {
  74590. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74591. time += scene.getEngine().getDeltaTime();
  74592. if (outputLiminance < 0) {
  74593. outputLiminance = _this._hdrCurrentLuminance;
  74594. }
  74595. else {
  74596. var dt = (lastTime - time) / 1000.0;
  74597. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74598. outputLiminance += _this.hdrDecreaseRate * dt;
  74599. }
  74600. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74601. outputLiminance -= _this.hdrIncreaseRate * dt;
  74602. }
  74603. else {
  74604. outputLiminance = _this._hdrCurrentLuminance;
  74605. }
  74606. }
  74607. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74608. effect.setFloat("averageLuminance", outputLiminance);
  74609. lastTime = time;
  74610. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74611. };
  74612. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74613. };
  74614. // Create lens flare post-process
  74615. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74616. var _this = this;
  74617. 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);
  74618. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74619. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74620. 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);
  74621. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74622. var resolution = new BABYLON.Vector2(0, 0);
  74623. // Lens flare
  74624. this.lensFlarePostProcess.onApply = function (effect) {
  74625. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74626. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74627. effect.setFloat("strength", _this.lensFlareStrength);
  74628. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74629. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74630. // Shift
  74631. resolution.x = _this.lensFlarePostProcess.width;
  74632. resolution.y = _this.lensFlarePostProcess.height;
  74633. effect.setVector2("resolution", resolution);
  74634. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74635. };
  74636. // Compose
  74637. 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);
  74638. 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);
  74639. this.lensFlareComposePostProcess.onApply = function (effect) {
  74640. if (!_this._scene.activeCamera) {
  74641. return;
  74642. }
  74643. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74644. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74645. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74646. // Lens start rotation matrix
  74647. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74648. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74649. 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));
  74650. camRot *= 4.0;
  74651. 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);
  74652. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74653. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74654. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74655. };
  74656. };
  74657. // Create depth-of-field post-process
  74658. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74659. var _this = this;
  74660. 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);
  74661. this.depthOfFieldPostProcess.onApply = function (effect) {
  74662. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74663. effect.setTexture("depthSampler", _this._getDepthTexture());
  74664. effect.setFloat("distance", _this.depthOfFieldDistance);
  74665. };
  74666. // Add to pipeline
  74667. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74668. };
  74669. // Create motion blur post-process
  74670. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74671. var _this = this;
  74672. 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);
  74673. var motionScale = 0;
  74674. var prevViewProjection = BABYLON.Matrix.Identity();
  74675. var invViewProjection = BABYLON.Matrix.Identity();
  74676. var viewProjection = BABYLON.Matrix.Identity();
  74677. var screenSize = BABYLON.Vector2.Zero();
  74678. this.motionBlurPostProcess.onApply = function (effect) {
  74679. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74680. viewProjection.invertToRef(invViewProjection);
  74681. effect.setMatrix("inverseViewProjection", invViewProjection);
  74682. effect.setMatrix("prevViewProjection", prevViewProjection);
  74683. prevViewProjection = viewProjection;
  74684. screenSize.x = _this.motionBlurPostProcess.width;
  74685. screenSize.y = _this.motionBlurPostProcess.height;
  74686. effect.setVector2("screenSize", screenSize);
  74687. motionScale = scene.getEngine().getFps() / 60.0;
  74688. effect.setFloat("motionScale", motionScale);
  74689. effect.setFloat("motionStrength", _this.motionStrength);
  74690. effect.setTexture("depthSampler", _this._getDepthTexture());
  74691. };
  74692. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74693. };
  74694. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74695. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74696. var renderer = this._scene.enableGeometryBufferRenderer();
  74697. return renderer.getGBuffer().textures[0];
  74698. }
  74699. return this._scene.enableDepthRenderer().getDepthMap();
  74700. };
  74701. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74702. for (var i = 0; i < this._cameras.length; i++) {
  74703. var camera = this._cameras[i];
  74704. if (this.originalPostProcess) {
  74705. this.originalPostProcess.dispose(camera);
  74706. }
  74707. if (this.downSampleX4PostProcess) {
  74708. this.downSampleX4PostProcess.dispose(camera);
  74709. }
  74710. if (this.brightPassPostProcess) {
  74711. this.brightPassPostProcess.dispose(camera);
  74712. }
  74713. if (this.textureAdderPostProcess) {
  74714. this.textureAdderPostProcess.dispose(camera);
  74715. }
  74716. if (this.textureAdderFinalPostProcess) {
  74717. this.textureAdderFinalPostProcess.dispose(camera);
  74718. }
  74719. if (this.volumetricLightPostProcess) {
  74720. this.volumetricLightPostProcess.dispose(camera);
  74721. }
  74722. if (this.volumetricLightSmoothXPostProcess) {
  74723. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74724. }
  74725. if (this.volumetricLightSmoothYPostProcess) {
  74726. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74727. }
  74728. if (this.volumetricLightMergePostProces) {
  74729. this.volumetricLightMergePostProces.dispose(camera);
  74730. }
  74731. if (this.volumetricLightFinalPostProcess) {
  74732. this.volumetricLightFinalPostProcess.dispose(camera);
  74733. }
  74734. if (this.lensFlarePostProcess) {
  74735. this.lensFlarePostProcess.dispose(camera);
  74736. }
  74737. if (this.lensFlareComposePostProcess) {
  74738. this.lensFlareComposePostProcess.dispose(camera);
  74739. }
  74740. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74741. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74742. }
  74743. if (this.luminancePostProcess) {
  74744. this.luminancePostProcess.dispose(camera);
  74745. }
  74746. if (this.hdrPostProcess) {
  74747. this.hdrPostProcess.dispose(camera);
  74748. }
  74749. if (this.hdrFinalPostProcess) {
  74750. this.hdrFinalPostProcess.dispose(camera);
  74751. }
  74752. if (this.depthOfFieldPostProcess) {
  74753. this.depthOfFieldPostProcess.dispose(camera);
  74754. }
  74755. if (this.motionBlurPostProcess) {
  74756. this.motionBlurPostProcess.dispose(camera);
  74757. }
  74758. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74759. this.blurHPostProcesses[j].dispose(camera);
  74760. }
  74761. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74762. this.blurVPostProcesses[j].dispose(camera);
  74763. }
  74764. }
  74765. this.originalPostProcess = null;
  74766. this.downSampleX4PostProcess = null;
  74767. this.brightPassPostProcess = null;
  74768. this.textureAdderPostProcess = null;
  74769. this.textureAdderFinalPostProcess = null;
  74770. this.volumetricLightPostProcess = null;
  74771. this.volumetricLightSmoothXPostProcess = null;
  74772. this.volumetricLightSmoothYPostProcess = null;
  74773. this.volumetricLightMergePostProces = null;
  74774. this.volumetricLightFinalPostProcess = null;
  74775. this.lensFlarePostProcess = null;
  74776. this.lensFlareComposePostProcess = null;
  74777. this.luminancePostProcess = null;
  74778. this.hdrPostProcess = null;
  74779. this.hdrFinalPostProcess = null;
  74780. this.depthOfFieldPostProcess = null;
  74781. this.motionBlurPostProcess = null;
  74782. this.luminanceDownSamplePostProcesses = [];
  74783. this.blurHPostProcesses = [];
  74784. this.blurVPostProcesses = [];
  74785. };
  74786. /**
  74787. * Dispose of the pipeline and stop all post processes
  74788. */
  74789. StandardRenderingPipeline.prototype.dispose = function () {
  74790. this._disposePostProcesses();
  74791. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74792. _super.prototype.dispose.call(this);
  74793. };
  74794. /**
  74795. * Serialize the rendering pipeline (Used when exporting)
  74796. * @returns the serialized object
  74797. */
  74798. StandardRenderingPipeline.prototype.serialize = function () {
  74799. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74800. if (this.sourceLight) {
  74801. serializationObject.sourceLightId = this.sourceLight.id;
  74802. }
  74803. serializationObject.customType = "StandardRenderingPipeline";
  74804. return serializationObject;
  74805. };
  74806. /**
  74807. * Parse the serialized pipeline
  74808. * @param source Source pipeline.
  74809. * @param scene The scene to load the pipeline to.
  74810. * @param rootUrl The URL of the serialized pipeline.
  74811. * @returns An instantiated pipeline from the serialized object.
  74812. */
  74813. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74814. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74815. if (source.sourceLightId) {
  74816. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74817. }
  74818. return p;
  74819. };
  74820. // Luminance steps
  74821. StandardRenderingPipeline.LuminanceSteps = 6;
  74822. __decorate([
  74823. BABYLON.serialize()
  74824. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74825. __decorate([
  74826. BABYLON.serialize()
  74827. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74828. __decorate([
  74829. BABYLON.serialize()
  74830. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74831. __decorate([
  74832. BABYLON.serialize()
  74833. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74834. __decorate([
  74835. BABYLON.serializeAsTexture("lensTexture")
  74836. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74837. __decorate([
  74838. BABYLON.serialize()
  74839. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74840. __decorate([
  74841. BABYLON.serialize()
  74842. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74843. __decorate([
  74844. BABYLON.serialize()
  74845. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74846. __decorate([
  74847. BABYLON.serialize()
  74848. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74849. __decorate([
  74850. BABYLON.serialize()
  74851. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74852. __decorate([
  74853. BABYLON.serialize()
  74854. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74855. __decorate([
  74856. BABYLON.serializeAsTexture("lensColorTexture")
  74857. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74858. __decorate([
  74859. BABYLON.serialize()
  74860. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74861. __decorate([
  74862. BABYLON.serialize()
  74863. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74864. __decorate([
  74865. BABYLON.serialize()
  74866. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74867. __decorate([
  74868. BABYLON.serialize()
  74869. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74870. __decorate([
  74871. BABYLON.serializeAsTexture("lensStarTexture")
  74872. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74873. __decorate([
  74874. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74875. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74876. __decorate([
  74877. BABYLON.serialize()
  74878. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74879. __decorate([
  74880. BABYLON.serialize()
  74881. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74882. __decorate([
  74883. BABYLON.serialize()
  74884. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74885. __decorate([
  74886. BABYLON.serialize()
  74887. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74888. __decorate([
  74889. BABYLON.serialize()
  74890. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74891. __decorate([
  74892. BABYLON.serialize()
  74893. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74894. __decorate([
  74895. BABYLON.serialize()
  74896. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74897. __decorate([
  74898. BABYLON.serialize()
  74899. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74900. __decorate([
  74901. BABYLON.serialize()
  74902. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74903. __decorate([
  74904. BABYLON.serialize()
  74905. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74906. __decorate([
  74907. BABYLON.serialize()
  74908. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74909. __decorate([
  74910. BABYLON.serialize()
  74911. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74912. return StandardRenderingPipeline;
  74913. }(BABYLON.PostProcessRenderPipeline));
  74914. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74915. })(BABYLON || (BABYLON = {}));
  74916. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74917. var BABYLON;
  74918. (function (BABYLON) {
  74919. var FxaaPostProcess = /** @class */ (function (_super) {
  74920. __extends(FxaaPostProcess, _super);
  74921. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74922. if (camera === void 0) { camera = null; }
  74923. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74924. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74925. var defines = _this._getDefines();
  74926. _this.updateEffect(defines);
  74927. _this.onApplyObservable.add(function (effect) {
  74928. var texelSize = _this.texelSize;
  74929. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74930. });
  74931. return _this;
  74932. }
  74933. FxaaPostProcess.prototype._getDefines = function () {
  74934. var engine = this.getEngine();
  74935. if (!engine) {
  74936. return null;
  74937. }
  74938. var glInfo = engine.getGlInfo();
  74939. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74940. return "#define MALI 1\n";
  74941. }
  74942. return null;
  74943. };
  74944. return FxaaPostProcess;
  74945. }(BABYLON.PostProcess));
  74946. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74947. })(BABYLON || (BABYLON = {}));
  74948. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74949. var BABYLON;
  74950. (function (BABYLON) {
  74951. /**
  74952. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74953. */
  74954. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74955. __extends(ChromaticAberrationPostProcess, _super);
  74956. /**
  74957. * Creates a new instance ChromaticAberrationPostProcess
  74958. * @param name The name of the effect.
  74959. * @param screenWidth The width of the screen to apply the effect on.
  74960. * @param screenHeight The height of the screen to apply the effect on.
  74961. * @param options The required width/height ratio to downsize to before computing the render pass.
  74962. * @param camera The camera to apply the render pass to.
  74963. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74964. * @param engine The engine which the post process will be applied. (default: current engine)
  74965. * @param reusable If the post process can be reused on the same frame. (default: false)
  74966. * @param textureType Type of textures used when performing the post process. (default: 0)
  74967. * @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)
  74968. */
  74969. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74970. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74971. if (blockCompilation === void 0) { blockCompilation = false; }
  74972. 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;
  74973. /**
  74974. * The amount of seperation of rgb channels (default: 30)
  74975. */
  74976. _this.aberrationAmount = 30;
  74977. /**
  74978. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74979. */
  74980. _this.radialIntensity = 0;
  74981. /**
  74982. * 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))
  74983. */
  74984. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74985. /**
  74986. * 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))
  74987. */
  74988. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74989. _this.onApplyObservable.add(function (effect) {
  74990. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74991. effect.setFloat('screen_width', screenWidth);
  74992. effect.setFloat('screen_height', screenHeight);
  74993. effect.setFloat('radialIntensity', _this.radialIntensity);
  74994. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74995. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74996. });
  74997. return _this;
  74998. }
  74999. return ChromaticAberrationPostProcess;
  75000. }(BABYLON.PostProcess));
  75001. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75002. })(BABYLON || (BABYLON = {}));
  75003. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75004. var BABYLON;
  75005. (function (BABYLON) {
  75006. /**
  75007. * The GrainPostProcess adds noise to the image at mid luminance levels
  75008. */
  75009. var GrainPostProcess = /** @class */ (function (_super) {
  75010. __extends(GrainPostProcess, _super);
  75011. /**
  75012. * Creates a new instance of @see GrainPostProcess
  75013. * @param name The name of the effect.
  75014. * @param options The required width/height ratio to downsize to before computing the render pass.
  75015. * @param camera The camera to apply the render pass to.
  75016. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75017. * @param engine The engine which the post process will be applied. (default: current engine)
  75018. * @param reusable If the post process can be reused on the same frame. (default: false)
  75019. * @param textureType Type of textures used when performing the post process. (default: 0)
  75020. * @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)
  75021. */
  75022. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75023. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75024. if (blockCompilation === void 0) { blockCompilation = false; }
  75025. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75026. /**
  75027. * The intensity of the grain added (default: 30)
  75028. */
  75029. _this.intensity = 30;
  75030. /**
  75031. * If the grain should be randomized on every frame
  75032. */
  75033. _this.animated = false;
  75034. _this.onApplyObservable.add(function (effect) {
  75035. effect.setFloat('intensity', _this.intensity);
  75036. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75037. });
  75038. return _this;
  75039. }
  75040. return GrainPostProcess;
  75041. }(BABYLON.PostProcess));
  75042. BABYLON.GrainPostProcess = GrainPostProcess;
  75043. })(BABYLON || (BABYLON = {}));
  75044. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75045. var BABYLON;
  75046. (function (BABYLON) {
  75047. /**
  75048. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75049. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75050. */
  75051. var SharpenPostProcess = /** @class */ (function (_super) {
  75052. __extends(SharpenPostProcess, _super);
  75053. /**
  75054. * Creates a new instance ConvolutionPostProcess
  75055. * @param name The name of the effect.
  75056. * @param options The required width/height ratio to downsize to before computing the render pass.
  75057. * @param camera The camera to apply the render pass to.
  75058. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75059. * @param engine The engine which the post process will be applied. (default: current engine)
  75060. * @param reusable If the post process can be reused on the same frame. (default: false)
  75061. * @param textureType Type of textures used when performing the post process. (default: 0)
  75062. * @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)
  75063. */
  75064. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75065. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75066. if (blockCompilation === void 0) { blockCompilation = false; }
  75067. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75068. /**
  75069. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75070. */
  75071. _this.colorAmount = 1.0;
  75072. /**
  75073. * How much sharpness should be applied (default: 0.3)
  75074. */
  75075. _this.edgeAmount = 0.3;
  75076. _this.onApply = function (effect) {
  75077. effect.setFloat2("screenSize", _this.width, _this.height);
  75078. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75079. };
  75080. return _this;
  75081. }
  75082. return SharpenPostProcess;
  75083. }(BABYLON.PostProcess));
  75084. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75085. })(BABYLON || (BABYLON = {}));
  75086. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75087. var BABYLON;
  75088. (function (BABYLON) {
  75089. /**
  75090. * The Blur Post Process which blurs an image based on a kernel and direction.
  75091. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75092. */
  75093. var BlurPostProcess = /** @class */ (function (_super) {
  75094. __extends(BlurPostProcess, _super);
  75095. /**
  75096. * Creates a new instance BlurPostProcess
  75097. * @param name The name of the effect.
  75098. * @param direction The direction in which to blur the image.
  75099. * @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.
  75100. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75101. * @param camera The camera to apply the render pass to.
  75102. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75103. * @param engine The engine which the post process will be applied. (default: current engine)
  75104. * @param reusable If the post process can be reused on the same frame. (default: false)
  75105. * @param textureType Type of textures used when performing the post process. (default: 0)
  75106. * @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)
  75107. */
  75108. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75109. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75110. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75111. if (defines === void 0) { defines = ""; }
  75112. if (blockCompilation === void 0) { blockCompilation = false; }
  75113. 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;
  75114. _this.direction = direction;
  75115. _this.blockCompilation = blockCompilation;
  75116. _this._packedFloat = false;
  75117. _this._staticDefines = "";
  75118. _this._staticDefines = defines;
  75119. _this.onApplyObservable.add(function (effect) {
  75120. if (_this._outputTexture) {
  75121. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75122. }
  75123. else {
  75124. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75125. }
  75126. });
  75127. _this.kernel = kernel;
  75128. return _this;
  75129. }
  75130. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75131. /**
  75132. * Gets the length in pixels of the blur sample region
  75133. */
  75134. get: function () {
  75135. return this._idealKernel;
  75136. },
  75137. /**
  75138. * Sets the length in pixels of the blur sample region
  75139. */
  75140. set: function (v) {
  75141. if (this._idealKernel === v) {
  75142. return;
  75143. }
  75144. v = Math.max(v, 1);
  75145. this._idealKernel = v;
  75146. this._kernel = this._nearestBestKernel(v);
  75147. if (!this.blockCompilation) {
  75148. this._updateParameters();
  75149. }
  75150. },
  75151. enumerable: true,
  75152. configurable: true
  75153. });
  75154. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75155. /**
  75156. * Gets wether or not the blur is unpacking/repacking floats
  75157. */
  75158. get: function () {
  75159. return this._packedFloat;
  75160. },
  75161. /**
  75162. * Sets wether or not the blur needs to unpack/repack floats
  75163. */
  75164. set: function (v) {
  75165. if (this._packedFloat === v) {
  75166. return;
  75167. }
  75168. this._packedFloat = v;
  75169. if (!this.blockCompilation) {
  75170. this._updateParameters();
  75171. }
  75172. },
  75173. enumerable: true,
  75174. configurable: true
  75175. });
  75176. /**
  75177. * Updates the effect with the current post process compile time values and recompiles the shader.
  75178. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75179. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75180. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75181. * @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
  75182. * @param onCompiled Called when the shader has been compiled.
  75183. * @param onError Called if there is an error when compiling a shader.
  75184. */
  75185. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75186. if (defines === void 0) { defines = null; }
  75187. if (uniforms === void 0) { uniforms = null; }
  75188. if (samplers === void 0) { samplers = null; }
  75189. this._updateParameters(onCompiled, onError);
  75190. };
  75191. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75192. // Generate sampling offsets and weights
  75193. var N = this._kernel;
  75194. var centerIndex = (N - 1) / 2;
  75195. // Generate Gaussian sampling weights over kernel
  75196. var offsets = [];
  75197. var weights = [];
  75198. var totalWeight = 0;
  75199. for (var i = 0; i < N; i++) {
  75200. var u = i / (N - 1);
  75201. var w = this._gaussianWeight(u * 2.0 - 1);
  75202. offsets[i] = (i - centerIndex);
  75203. weights[i] = w;
  75204. totalWeight += w;
  75205. }
  75206. // Normalize weights
  75207. for (var i = 0; i < weights.length; i++) {
  75208. weights[i] /= totalWeight;
  75209. }
  75210. // Optimize: combine samples to take advantage of hardware linear sampling
  75211. // Walk from left to center, combining pairs (symmetrically)
  75212. var linearSamplingWeights = [];
  75213. var linearSamplingOffsets = [];
  75214. var linearSamplingMap = [];
  75215. for (var i = 0; i <= centerIndex; i += 2) {
  75216. var j = Math.min(i + 1, Math.floor(centerIndex));
  75217. var singleCenterSample = i === j;
  75218. if (singleCenterSample) {
  75219. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75220. }
  75221. else {
  75222. var sharedCell = j === centerIndex;
  75223. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75224. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75225. if (offsetLinear === 0) {
  75226. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75227. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75228. }
  75229. else {
  75230. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75231. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75232. }
  75233. }
  75234. }
  75235. for (var i = 0; i < linearSamplingMap.length; i++) {
  75236. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75237. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75238. }
  75239. // Replace with optimized
  75240. offsets = linearSamplingOffsets;
  75241. weights = linearSamplingWeights;
  75242. // Generate shaders
  75243. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75244. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75245. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75246. var defines = "";
  75247. defines += this._staticDefines;
  75248. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75249. if (this._staticDefines.indexOf("DOF") != -1) {
  75250. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75251. varyingCount--;
  75252. }
  75253. for (var i = 0; i < varyingCount; i++) {
  75254. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75255. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75256. }
  75257. var depCount = 0;
  75258. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75259. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75260. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75261. depCount++;
  75262. }
  75263. if (this.packedFloat) {
  75264. defines += "#define PACKEDFLOAT 1";
  75265. }
  75266. this.blockCompilation = false;
  75267. _super.prototype.updateEffect.call(this, defines, null, null, {
  75268. varyingCount: varyingCount,
  75269. depCount: depCount
  75270. }, onCompiled, onError);
  75271. };
  75272. /**
  75273. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75274. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75275. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75276. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75277. * The gaps between physical kernels are compensated for in the weighting of the samples
  75278. * @param idealKernel Ideal blur kernel.
  75279. * @return Nearest best kernel.
  75280. */
  75281. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75282. var v = Math.round(idealKernel);
  75283. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75284. var k = _a[_i];
  75285. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75286. return Math.max(k, 3);
  75287. }
  75288. }
  75289. return Math.max(v, 3);
  75290. };
  75291. /**
  75292. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75293. * @param x The point on the Gaussian distribution to sample.
  75294. * @return the value of the Gaussian function at x.
  75295. */
  75296. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75297. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75298. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75299. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75300. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75301. // truncated at around 1.3% of peak strength.
  75302. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75303. var sigma = (1 / 3);
  75304. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75305. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75306. var weight = (1.0 / denominator) * Math.exp(exponent);
  75307. return weight;
  75308. };
  75309. /**
  75310. * Generates a string that can be used as a floating point number in GLSL.
  75311. * @param x Value to print.
  75312. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75313. * @return GLSL float string.
  75314. */
  75315. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75316. if (decimalFigures === void 0) { decimalFigures = 8; }
  75317. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75318. };
  75319. return BlurPostProcess;
  75320. }(BABYLON.PostProcess));
  75321. BABYLON.BlurPostProcess = BlurPostProcess;
  75322. })(BABYLON || (BABYLON = {}));
  75323. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75324. var BABYLON;
  75325. (function (BABYLON) {
  75326. /**
  75327. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75328. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75329. * based on samples that have a large difference in distance than the center pixel.
  75330. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75331. */
  75332. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75333. __extends(DepthOfFieldBlurPostProcess, _super);
  75334. /**
  75335. * Creates a new instance CircleOfConfusionPostProcess
  75336. * @param name The name of the effect.
  75337. * @param scene The scene the effect belongs to.
  75338. * @param direction The direction the blur should be applied.
  75339. * @param kernel The size of the kernel used to blur.
  75340. * @param options The required width/height ratio to downsize to before computing the render pass.
  75341. * @param camera The camera to apply the render pass to.
  75342. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75343. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75344. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75345. * @param engine The engine which the post process will be applied. (default: current engine)
  75346. * @param reusable If the post process can be reused on the same frame. (default: false)
  75347. * @param textureType Type of textures used when performing the post process. (default: 0)
  75348. * @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)
  75349. */
  75350. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75351. if (imageToBlur === void 0) { imageToBlur = null; }
  75352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75353. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75354. if (blockCompilation === void 0) { blockCompilation = false; }
  75355. 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;
  75356. _this.direction = direction;
  75357. _this.onApplyObservable.add(function (effect) {
  75358. if (imageToBlur != null) {
  75359. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75360. }
  75361. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75362. if (scene.activeCamera) {
  75363. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75364. }
  75365. });
  75366. return _this;
  75367. }
  75368. return DepthOfFieldBlurPostProcess;
  75369. }(BABYLON.BlurPostProcess));
  75370. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75371. })(BABYLON || (BABYLON = {}));
  75372. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75373. var BABYLON;
  75374. (function (BABYLON) {
  75375. /**
  75376. * Options to be set when merging outputs from the default pipeline.
  75377. */
  75378. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75379. function DepthOfFieldMergePostProcessOptions() {
  75380. }
  75381. return DepthOfFieldMergePostProcessOptions;
  75382. }());
  75383. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75384. /**
  75385. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75386. */
  75387. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75388. __extends(DepthOfFieldMergePostProcess, _super);
  75389. /**
  75390. * Creates a new instance of DepthOfFieldMergePostProcess
  75391. * @param name The name of the effect.
  75392. * @param originalFromInput Post process which's input will be used for the merge.
  75393. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75394. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75395. * @param options The required width/height ratio to downsize to before computing the render pass.
  75396. * @param camera The camera to apply the render pass to.
  75397. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75398. * @param engine The engine which the post process will be applied. (default: current engine)
  75399. * @param reusable If the post process can be reused on the same frame. (default: false)
  75400. * @param textureType Type of textures used when performing the post process. (default: 0)
  75401. * @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)
  75402. */
  75403. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75404. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75405. if (blockCompilation === void 0) { blockCompilation = false; }
  75406. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75407. _this.blurSteps = blurSteps;
  75408. _this.onApplyObservable.add(function (effect) {
  75409. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75410. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75411. blurSteps.forEach(function (step, index) {
  75412. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75413. });
  75414. });
  75415. if (!blockCompilation) {
  75416. _this.updateEffect();
  75417. }
  75418. return _this;
  75419. }
  75420. /**
  75421. * Updates the effect with the current post process compile time values and recompiles the shader.
  75422. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75423. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75424. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75425. * @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
  75426. * @param onCompiled Called when the shader has been compiled.
  75427. * @param onError Called if there is an error when compiling a shader.
  75428. */
  75429. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75430. if (defines === void 0) { defines = null; }
  75431. if (uniforms === void 0) { uniforms = null; }
  75432. if (samplers === void 0) { samplers = null; }
  75433. if (!defines) {
  75434. defines = "";
  75435. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75436. }
  75437. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75438. };
  75439. return DepthOfFieldMergePostProcess;
  75440. }(BABYLON.PostProcess));
  75441. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75442. })(BABYLON || (BABYLON = {}));
  75443. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75444. var BABYLON;
  75445. (function (BABYLON) {
  75446. /**
  75447. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75448. */
  75449. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75450. __extends(CircleOfConfusionPostProcess, _super);
  75451. /**
  75452. * Creates a new instance CircleOfConfusionPostProcess
  75453. * @param name The name of the effect.
  75454. * @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.
  75455. * @param options The required width/height ratio to downsize to before computing the render pass.
  75456. * @param camera The camera to apply the render pass to.
  75457. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75458. * @param engine The engine which the post process will be applied. (default: current engine)
  75459. * @param reusable If the post process can be reused on the same frame. (default: false)
  75460. * @param textureType Type of textures used when performing the post process. (default: 0)
  75461. * @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)
  75462. */
  75463. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75464. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75465. if (blockCompilation === void 0) { blockCompilation = false; }
  75466. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75467. /**
  75468. * 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.
  75469. */
  75470. _this.lensSize = 50;
  75471. /**
  75472. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75473. */
  75474. _this.fStop = 1.4;
  75475. /**
  75476. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75477. */
  75478. _this.focusDistance = 2000;
  75479. /**
  75480. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75481. */
  75482. _this.focalLength = 50;
  75483. _this._depthTexture = null;
  75484. _this._depthTexture = depthTexture;
  75485. _this.onApplyObservable.add(function (effect) {
  75486. if (!_this._depthTexture) {
  75487. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75488. return;
  75489. }
  75490. effect.setTexture("depthSampler", _this._depthTexture);
  75491. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75492. var aperture = _this.lensSize / _this.fStop;
  75493. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75494. effect.setFloat('focusDistance', _this.focusDistance);
  75495. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75496. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75497. });
  75498. return _this;
  75499. }
  75500. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75501. /**
  75502. * 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.
  75503. */
  75504. set: function (value) {
  75505. this._depthTexture = value;
  75506. },
  75507. enumerable: true,
  75508. configurable: true
  75509. });
  75510. return CircleOfConfusionPostProcess;
  75511. }(BABYLON.PostProcess));
  75512. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75513. })(BABYLON || (BABYLON = {}));
  75514. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75515. var BABYLON;
  75516. (function (BABYLON) {
  75517. /**
  75518. * Specifies the level of max blur that should be applied when using the depth of field effect
  75519. */
  75520. var DepthOfFieldEffectBlurLevel;
  75521. (function (DepthOfFieldEffectBlurLevel) {
  75522. /**
  75523. * Subtle blur
  75524. */
  75525. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75526. /**
  75527. * Medium blur
  75528. */
  75529. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75530. /**
  75531. * Large blur
  75532. */
  75533. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75534. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75535. ;
  75536. /**
  75537. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75538. */
  75539. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75540. __extends(DepthOfFieldEffect, _super);
  75541. /**
  75542. * Creates a new instance DepthOfFieldEffect
  75543. * @param scene The scene the effect belongs to.
  75544. * @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.
  75545. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75546. * @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)
  75547. */
  75548. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75549. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75550. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75551. if (blockCompilation === void 0) { blockCompilation = false; }
  75552. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75553. return _this._effects;
  75554. }, true) || this;
  75555. /**
  75556. * Internal post processes in depth of field effect
  75557. */
  75558. _this._effects = [];
  75559. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75560. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75561. // 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)
  75562. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75563. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75564. _this._depthOfFieldBlurY = [];
  75565. _this._depthOfFieldBlurX = [];
  75566. var blurCount = 1;
  75567. var kernelSize = 15;
  75568. switch (blurLevel) {
  75569. case DepthOfFieldEffectBlurLevel.High: {
  75570. blurCount = 3;
  75571. kernelSize = 51;
  75572. break;
  75573. }
  75574. case DepthOfFieldEffectBlurLevel.Medium: {
  75575. blurCount = 2;
  75576. kernelSize = 31;
  75577. break;
  75578. }
  75579. default: {
  75580. kernelSize = 15;
  75581. blurCount = 1;
  75582. break;
  75583. }
  75584. }
  75585. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75586. var ratio = 1.0;
  75587. for (var i = 0; i < blurCount; i++) {
  75588. 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);
  75589. blurY.autoClear = false;
  75590. ratio = 0.75 / Math.pow(2, i);
  75591. 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);
  75592. blurX.autoClear = false;
  75593. _this._depthOfFieldBlurY.push(blurY);
  75594. _this._depthOfFieldBlurX.push(blurX);
  75595. }
  75596. // Set all post processes on the effect.
  75597. _this._effects = [_this._circleOfConfusion];
  75598. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75599. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75600. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75601. }
  75602. // Merge blurred images with original image based on circleOfConfusion
  75603. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75604. _this._dofMerge.autoClear = false;
  75605. _this._effects.push(_this._dofMerge);
  75606. return _this;
  75607. }
  75608. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75609. get: function () {
  75610. return this._circleOfConfusion.focalLength;
  75611. },
  75612. /**
  75613. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75614. */
  75615. set: function (value) {
  75616. this._circleOfConfusion.focalLength = value;
  75617. },
  75618. enumerable: true,
  75619. configurable: true
  75620. });
  75621. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75622. get: function () {
  75623. return this._circleOfConfusion.fStop;
  75624. },
  75625. /**
  75626. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75627. */
  75628. set: function (value) {
  75629. this._circleOfConfusion.fStop = value;
  75630. },
  75631. enumerable: true,
  75632. configurable: true
  75633. });
  75634. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75635. get: function () {
  75636. return this._circleOfConfusion.focusDistance;
  75637. },
  75638. /**
  75639. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75640. */
  75641. set: function (value) {
  75642. this._circleOfConfusion.focusDistance = value;
  75643. },
  75644. enumerable: true,
  75645. configurable: true
  75646. });
  75647. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75648. get: function () {
  75649. return this._circleOfConfusion.lensSize;
  75650. },
  75651. /**
  75652. * 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.
  75653. */
  75654. set: function (value) {
  75655. this._circleOfConfusion.lensSize = value;
  75656. },
  75657. enumerable: true,
  75658. configurable: true
  75659. });
  75660. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75661. /**
  75662. * 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.
  75663. */
  75664. set: function (value) {
  75665. this._circleOfConfusion.depthTexture = value;
  75666. },
  75667. enumerable: true,
  75668. configurable: true
  75669. });
  75670. /**
  75671. * Disposes each of the internal effects for a given camera.
  75672. * @param camera The camera to dispose the effect on.
  75673. */
  75674. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75675. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75676. this._effects[effectIndex].dispose(camera);
  75677. }
  75678. };
  75679. /**
  75680. * Internal
  75681. */
  75682. DepthOfFieldEffect.prototype._updateEffects = function () {
  75683. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75684. this._effects[effectIndex].updateEffect();
  75685. }
  75686. };
  75687. /**
  75688. * Internal
  75689. * @returns if all the contained post processes are ready.
  75690. */
  75691. DepthOfFieldEffect.prototype._isReady = function () {
  75692. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75693. if (!this._effects[effectIndex].isReady()) {
  75694. return false;
  75695. }
  75696. }
  75697. return true;
  75698. };
  75699. return DepthOfFieldEffect;
  75700. }(BABYLON.PostProcessRenderEffect));
  75701. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75702. })(BABYLON || (BABYLON = {}));
  75703. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75704. var BABYLON;
  75705. (function (BABYLON) {
  75706. /**
  75707. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75708. */
  75709. var BloomMergePostProcess = /** @class */ (function (_super) {
  75710. __extends(BloomMergePostProcess, _super);
  75711. /**
  75712. * Creates a new instance of @see BloomMergePostProcess
  75713. * @param name The name of the effect.
  75714. * @param originalFromInput Post process which's input will be used for the merge.
  75715. * @param blurred Blurred highlights post process which's output will be used.
  75716. * @param weight Weight of the bloom to be added to the original input.
  75717. * @param options The required width/height ratio to downsize to before computing the render pass.
  75718. * @param camera The camera to apply the render pass to.
  75719. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75720. * @param engine The engine which the post process will be applied. (default: current engine)
  75721. * @param reusable If the post process can be reused on the same frame. (default: false)
  75722. * @param textureType Type of textures used when performing the post process. (default: 0)
  75723. * @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)
  75724. */
  75725. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75726. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75727. if (blockCompilation === void 0) { blockCompilation = false; }
  75728. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75729. _this.weight = weight;
  75730. _this.onApplyObservable.add(function (effect) {
  75731. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75732. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75733. effect.setFloat("bloomWeight", _this.weight);
  75734. });
  75735. if (!blockCompilation) {
  75736. _this.updateEffect();
  75737. }
  75738. return _this;
  75739. }
  75740. return BloomMergePostProcess;
  75741. }(BABYLON.PostProcess));
  75742. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75743. })(BABYLON || (BABYLON = {}));
  75744. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75745. var BABYLON;
  75746. (function (BABYLON) {
  75747. /**
  75748. * 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.
  75749. */
  75750. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75751. __extends(ExtractHighlightsPostProcess, _super);
  75752. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75753. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75754. if (blockCompilation === void 0) { blockCompilation = false; }
  75755. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75756. /**
  75757. * The luminance threshold, pixels below this value will be set to black.
  75758. */
  75759. _this.threshold = 0.9;
  75760. /**
  75761. * Internal
  75762. */
  75763. _this._exposure = 1;
  75764. /**
  75765. * Post process which has the input texture to be used when performing highlight extraction
  75766. */
  75767. _this._inputPostProcess = null;
  75768. _this.onApplyObservable.add(function (effect) {
  75769. if (_this._inputPostProcess) {
  75770. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75771. }
  75772. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75773. effect.setFloat('exposure', _this._exposure);
  75774. });
  75775. return _this;
  75776. }
  75777. return ExtractHighlightsPostProcess;
  75778. }(BABYLON.PostProcess));
  75779. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75780. })(BABYLON || (BABYLON = {}));
  75781. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75782. var BABYLON;
  75783. (function (BABYLON) {
  75784. /**
  75785. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75786. */
  75787. var BloomEffect = /** @class */ (function (_super) {
  75788. __extends(BloomEffect, _super);
  75789. /**
  75790. * Creates a new instance of @see BloomEffect
  75791. * @param scene The scene the effect belongs to.
  75792. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75793. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75794. * @param bloomWeight The the strength of bloom.
  75795. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75796. * @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)
  75797. */
  75798. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75799. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75800. if (blockCompilation === void 0) { blockCompilation = false; }
  75801. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75802. return _this._effects;
  75803. }, true) || this;
  75804. _this.bloomScale = bloomScale;
  75805. /**
  75806. * Internal
  75807. */
  75808. _this._effects = [];
  75809. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75810. _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);
  75811. _this._blurX.alwaysForcePOT = true;
  75812. _this._blurX.autoClear = false;
  75813. _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);
  75814. _this._blurY.alwaysForcePOT = true;
  75815. _this._blurY.autoClear = false;
  75816. _this.kernel = bloomKernel;
  75817. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75818. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75819. _this._merge.autoClear = false;
  75820. _this._effects.push(_this._merge);
  75821. return _this;
  75822. }
  75823. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75824. /**
  75825. * The luminance threshold to find bright areas of the image to bloom.
  75826. */
  75827. get: function () {
  75828. return this._downscale.threshold;
  75829. },
  75830. set: function (value) {
  75831. this._downscale.threshold = value;
  75832. },
  75833. enumerable: true,
  75834. configurable: true
  75835. });
  75836. Object.defineProperty(BloomEffect.prototype, "weight", {
  75837. /**
  75838. * The strength of the bloom.
  75839. */
  75840. get: function () {
  75841. return this._merge.weight;
  75842. },
  75843. set: function (value) {
  75844. this._merge.weight = value;
  75845. },
  75846. enumerable: true,
  75847. configurable: true
  75848. });
  75849. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75850. /**
  75851. * Specifies the size of the bloom blur kernel, relative to the final output size
  75852. */
  75853. get: function () {
  75854. return this._blurX.kernel / this.bloomScale;
  75855. },
  75856. set: function (value) {
  75857. this._blurX.kernel = value * this.bloomScale;
  75858. this._blurY.kernel = value * this.bloomScale;
  75859. },
  75860. enumerable: true,
  75861. configurable: true
  75862. });
  75863. /**
  75864. * Disposes each of the internal effects for a given camera.
  75865. * @param camera The camera to dispose the effect on.
  75866. */
  75867. BloomEffect.prototype.disposeEffects = function (camera) {
  75868. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75869. this._effects[effectIndex].dispose(camera);
  75870. }
  75871. };
  75872. /**
  75873. * Internal
  75874. */
  75875. BloomEffect.prototype._updateEffects = function () {
  75876. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75877. this._effects[effectIndex].updateEffect();
  75878. }
  75879. };
  75880. /**
  75881. * Internal
  75882. * @returns if all the contained post processes are ready.
  75883. */
  75884. BloomEffect.prototype._isReady = function () {
  75885. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75886. if (!this._effects[effectIndex].isReady()) {
  75887. return false;
  75888. }
  75889. }
  75890. return true;
  75891. };
  75892. return BloomEffect;
  75893. }(BABYLON.PostProcessRenderEffect));
  75894. BABYLON.BloomEffect = BloomEffect;
  75895. })(BABYLON || (BABYLON = {}));
  75896. //# sourceMappingURL=babylon.bloomEffect.js.map
  75897. var BABYLON;
  75898. (function (BABYLON) {
  75899. /**
  75900. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75901. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75902. */
  75903. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75904. __extends(DefaultRenderingPipeline, _super);
  75905. /**
  75906. * @constructor
  75907. * @param {string} name - The rendering pipeline name (default: "")
  75908. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75909. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75910. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75911. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75912. */
  75913. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75914. if (name === void 0) { name = ""; }
  75915. if (hdr === void 0) { hdr = true; }
  75916. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75917. if (automaticBuild === void 0) { automaticBuild = true; }
  75918. var _this = _super.call(this, scene.getEngine(), name) || this;
  75919. _this._originalCameras = [];
  75920. /**
  75921. * ID of the sharpen post process,
  75922. */
  75923. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75924. /**
  75925. * ID of the image processing post process;
  75926. */
  75927. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75928. /**
  75929. * ID of the Fast Approximate Anti-Aliasing post process;
  75930. */
  75931. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75932. /**
  75933. * ID of the chromatic aberration post process,
  75934. */
  75935. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75936. /**
  75937. * ID of the grain post process
  75938. */
  75939. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75940. /**
  75941. * Glow post process which adds a glow to emmisive areas of the image
  75942. */
  75943. _this._glowLayer = null;
  75944. /**
  75945. * Animations which can be used to tweak settings over a period of time
  75946. */
  75947. _this.animations = [];
  75948. _this._imageProcessingConfigurationObserver = null;
  75949. // Values
  75950. _this._sharpenEnabled = false;
  75951. _this._bloomEnabled = false;
  75952. _this._depthOfFieldEnabled = false;
  75953. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75954. _this._fxaaEnabled = false;
  75955. _this._imageProcessingEnabled = true;
  75956. _this._bloomScale = 0.5;
  75957. _this._chromaticAberrationEnabled = false;
  75958. _this._grainEnabled = false;
  75959. _this._buildAllowed = true;
  75960. _this._resizeObserver = null;
  75961. _this._hardwareScaleLevel = 1.0;
  75962. _this._bloomKernel = 64;
  75963. /**
  75964. * Specifies the weight of the bloom in the final rendering
  75965. */
  75966. _this._bloomWeight = 0.15;
  75967. /**
  75968. * Specifies the luma threshold for the area that will be blurred by the bloom
  75969. */
  75970. _this._bloomThreshold = 0.9;
  75971. _this._samples = 1;
  75972. _this._hasCleared = false;
  75973. _this._prevPostProcess = null;
  75974. _this._prevPrevPostProcess = null;
  75975. _this._cameras = cameras || scene.cameras;
  75976. _this._originalCameras = _this._cameras.slice();
  75977. _this._buildAllowed = automaticBuild;
  75978. // Initialize
  75979. _this._scene = scene;
  75980. var caps = _this._scene.getEngine().getCaps();
  75981. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75982. // Misc
  75983. if (_this._hdr) {
  75984. if (caps.textureHalfFloatRender) {
  75985. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75986. }
  75987. else if (caps.textureFloatRender) {
  75988. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75989. }
  75990. }
  75991. else {
  75992. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75993. }
  75994. // Attach
  75995. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75996. var engine = _this._scene.getEngine();
  75997. // Create post processes before hand so they can be modified before enabled.
  75998. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75999. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76000. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76001. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76002. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76003. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76004. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76005. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76006. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76007. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76008. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76009. _this.bloomKernel = _this.bloomKernel;
  76010. });
  76011. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76012. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76013. });
  76014. _this._buildPipeline();
  76015. return _this;
  76016. }
  76017. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76018. get: function () {
  76019. return this._sharpenEnabled;
  76020. },
  76021. /**
  76022. * Enable or disable the sharpen process from the pipeline
  76023. */
  76024. set: function (enabled) {
  76025. if (this._sharpenEnabled === enabled) {
  76026. return;
  76027. }
  76028. this._sharpenEnabled = enabled;
  76029. this._buildPipeline();
  76030. },
  76031. enumerable: true,
  76032. configurable: true
  76033. });
  76034. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76035. /**
  76036. * Specifies the size of the bloom blur kernel, relative to the final output size
  76037. */
  76038. get: function () {
  76039. return this._bloomKernel;
  76040. },
  76041. set: function (value) {
  76042. this._bloomKernel = value;
  76043. this.bloom.kernel = value / this._hardwareScaleLevel;
  76044. },
  76045. enumerable: true,
  76046. configurable: true
  76047. });
  76048. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76049. get: function () {
  76050. return this._bloomWeight;
  76051. },
  76052. /**
  76053. * The strength of the bloom.
  76054. */
  76055. set: function (value) {
  76056. if (this._bloomWeight === value) {
  76057. return;
  76058. }
  76059. this.bloom.weight = value;
  76060. this._bloomWeight = value;
  76061. },
  76062. enumerable: true,
  76063. configurable: true
  76064. });
  76065. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76066. get: function () {
  76067. return this._bloomThreshold;
  76068. },
  76069. /**
  76070. * The strength of the bloom.
  76071. */
  76072. set: function (value) {
  76073. if (this._bloomThreshold === value) {
  76074. return;
  76075. }
  76076. this.bloom.threshold = value;
  76077. this._bloomThreshold = value;
  76078. },
  76079. enumerable: true,
  76080. configurable: true
  76081. });
  76082. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76083. get: function () {
  76084. return this._bloomScale;
  76085. },
  76086. /**
  76087. * The scale of the bloom, lower value will provide better performance.
  76088. */
  76089. set: function (value) {
  76090. if (this._bloomScale === value) {
  76091. return;
  76092. }
  76093. this._bloomScale = value;
  76094. // recreate bloom and dispose old as this setting is not dynamic
  76095. this._rebuildBloom();
  76096. this._buildPipeline();
  76097. },
  76098. enumerable: true,
  76099. configurable: true
  76100. });
  76101. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76102. get: function () {
  76103. return this._bloomEnabled;
  76104. },
  76105. /**
  76106. * Enable or disable the bloom from the pipeline
  76107. */
  76108. set: function (enabled) {
  76109. if (this._bloomEnabled === enabled) {
  76110. return;
  76111. }
  76112. this._bloomEnabled = enabled;
  76113. this._buildPipeline();
  76114. },
  76115. enumerable: true,
  76116. configurable: true
  76117. });
  76118. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76119. // recreate bloom and dispose old as this setting is not dynamic
  76120. var oldBloom = this.bloom;
  76121. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76122. this.bloom.threshold = oldBloom.threshold;
  76123. for (var i = 0; i < this._cameras.length; i++) {
  76124. oldBloom.disposeEffects(this._cameras[i]);
  76125. }
  76126. };
  76127. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76128. /**
  76129. * If the depth of field is enabled.
  76130. */
  76131. get: function () {
  76132. return this._depthOfFieldEnabled;
  76133. },
  76134. set: function (enabled) {
  76135. if (this._depthOfFieldEnabled === enabled) {
  76136. return;
  76137. }
  76138. this._depthOfFieldEnabled = enabled;
  76139. this._buildPipeline();
  76140. },
  76141. enumerable: true,
  76142. configurable: true
  76143. });
  76144. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76145. /**
  76146. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76147. */
  76148. get: function () {
  76149. return this._depthOfFieldBlurLevel;
  76150. },
  76151. set: function (value) {
  76152. if (this._depthOfFieldBlurLevel === value) {
  76153. return;
  76154. }
  76155. this._depthOfFieldBlurLevel = value;
  76156. // recreate dof and dispose old as this setting is not dynamic
  76157. var oldDof = this.depthOfField;
  76158. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76159. this.depthOfField.focalLength = oldDof.focalLength;
  76160. this.depthOfField.focusDistance = oldDof.focusDistance;
  76161. this.depthOfField.fStop = oldDof.fStop;
  76162. this.depthOfField.lensSize = oldDof.lensSize;
  76163. for (var i = 0; i < this._cameras.length; i++) {
  76164. oldDof.disposeEffects(this._cameras[i]);
  76165. }
  76166. this._buildPipeline();
  76167. },
  76168. enumerable: true,
  76169. configurable: true
  76170. });
  76171. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76172. get: function () {
  76173. return this._fxaaEnabled;
  76174. },
  76175. /**
  76176. * If the anti aliasing is enabled.
  76177. */
  76178. set: function (enabled) {
  76179. if (this._fxaaEnabled === enabled) {
  76180. return;
  76181. }
  76182. this._fxaaEnabled = enabled;
  76183. this._buildPipeline();
  76184. },
  76185. enumerable: true,
  76186. configurable: true
  76187. });
  76188. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76189. get: function () {
  76190. return this._samples;
  76191. },
  76192. /**
  76193. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76194. */
  76195. set: function (sampleCount) {
  76196. if (this._samples === sampleCount) {
  76197. return;
  76198. }
  76199. this._samples = sampleCount;
  76200. this._buildPipeline();
  76201. },
  76202. enumerable: true,
  76203. configurable: true
  76204. });
  76205. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76206. get: function () {
  76207. return this._imageProcessingEnabled;
  76208. },
  76209. /**
  76210. * If image processing is enabled.
  76211. */
  76212. set: function (enabled) {
  76213. if (this._imageProcessingEnabled === enabled) {
  76214. return;
  76215. }
  76216. this._imageProcessingEnabled = enabled;
  76217. this._buildPipeline();
  76218. },
  76219. enumerable: true,
  76220. configurable: true
  76221. });
  76222. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76223. get: function () {
  76224. return this._glowLayer == null;
  76225. },
  76226. /**
  76227. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76228. */
  76229. set: function (enabled) {
  76230. if (enabled && !this._glowLayer) {
  76231. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76232. }
  76233. else if (!enabled && this._glowLayer) {
  76234. this._glowLayer.dispose();
  76235. this._glowLayer = null;
  76236. }
  76237. },
  76238. enumerable: true,
  76239. configurable: true
  76240. });
  76241. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76242. get: function () {
  76243. return this._chromaticAberrationEnabled;
  76244. },
  76245. /**
  76246. * Enable or disable the chromaticAberration process from the pipeline
  76247. */
  76248. set: function (enabled) {
  76249. if (this._chromaticAberrationEnabled === enabled) {
  76250. return;
  76251. }
  76252. this._chromaticAberrationEnabled = enabled;
  76253. this._buildPipeline();
  76254. },
  76255. enumerable: true,
  76256. configurable: true
  76257. });
  76258. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76259. get: function () {
  76260. return this._grainEnabled;
  76261. },
  76262. /**
  76263. * Enable or disable the grain process from the pipeline
  76264. */
  76265. set: function (enabled) {
  76266. if (this._grainEnabled === enabled) {
  76267. return;
  76268. }
  76269. this._grainEnabled = enabled;
  76270. this._buildPipeline();
  76271. },
  76272. enumerable: true,
  76273. configurable: true
  76274. });
  76275. /**
  76276. * Force the compilation of the entire pipeline.
  76277. */
  76278. DefaultRenderingPipeline.prototype.prepare = function () {
  76279. var previousState = this._buildAllowed;
  76280. this._buildAllowed = true;
  76281. this._buildPipeline();
  76282. this._buildAllowed = previousState;
  76283. };
  76284. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76285. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76286. if (this._hasCleared) {
  76287. postProcess.autoClear = false;
  76288. }
  76289. else {
  76290. postProcess.autoClear = true;
  76291. this._scene.autoClear = false;
  76292. this._hasCleared = true;
  76293. }
  76294. if (!skipTextureSharing) {
  76295. if (this._prevPrevPostProcess) {
  76296. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76297. }
  76298. else {
  76299. postProcess.useOwnOutput();
  76300. }
  76301. if (this._prevPostProcess) {
  76302. this._prevPrevPostProcess = this._prevPostProcess;
  76303. }
  76304. this._prevPostProcess = postProcess;
  76305. }
  76306. };
  76307. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76308. var _this = this;
  76309. if (!this._buildAllowed) {
  76310. return;
  76311. }
  76312. this._scene.autoClear = true;
  76313. var engine = this._scene.getEngine();
  76314. this._disposePostProcesses();
  76315. if (this._cameras !== null) {
  76316. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76317. // get back cameras to be used to reattach pipeline
  76318. this._cameras = this._originalCameras.slice();
  76319. }
  76320. this._reset();
  76321. this._prevPostProcess = null;
  76322. this._prevPrevPostProcess = null;
  76323. this._hasCleared = false;
  76324. if (this.depthOfFieldEnabled) {
  76325. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76326. this.depthOfField.depthTexture = depthTexture;
  76327. if (!this.depthOfField._isReady()) {
  76328. this.depthOfField._updateEffects();
  76329. }
  76330. this.addEffect(this.depthOfField);
  76331. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76332. }
  76333. if (this.bloomEnabled) {
  76334. if (!this.bloom._isReady()) {
  76335. this.bloom._updateEffects();
  76336. }
  76337. this.addEffect(this.bloom);
  76338. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76339. }
  76340. if (this._imageProcessingEnabled) {
  76341. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76342. if (this._hdr) {
  76343. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76344. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76345. }
  76346. else {
  76347. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76348. }
  76349. }
  76350. if (this.sharpenEnabled) {
  76351. if (!this.sharpen.isReady()) {
  76352. this.sharpen.updateEffect();
  76353. }
  76354. this.addEffect(this._sharpenEffect);
  76355. this._setAutoClearAndTextureSharing(this.sharpen);
  76356. }
  76357. if (this.grainEnabled) {
  76358. if (!this.grain.isReady()) {
  76359. this.grain.updateEffect();
  76360. }
  76361. this.addEffect(this._grainEffect);
  76362. this._setAutoClearAndTextureSharing(this.grain);
  76363. }
  76364. if (this.chromaticAberrationEnabled) {
  76365. if (!this.chromaticAberration.isReady()) {
  76366. this.chromaticAberration.updateEffect();
  76367. }
  76368. this.addEffect(this._chromaticAberrationEffect);
  76369. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76370. }
  76371. if (this.fxaaEnabled) {
  76372. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76373. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76374. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76375. }
  76376. if (this._cameras !== null) {
  76377. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76378. }
  76379. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76380. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76381. }
  76382. };
  76383. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76384. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76385. for (var i = 0; i < this._cameras.length; i++) {
  76386. var camera = this._cameras[i];
  76387. if (this.imageProcessing) {
  76388. this.imageProcessing.dispose(camera);
  76389. }
  76390. if (this.fxaa) {
  76391. this.fxaa.dispose(camera);
  76392. }
  76393. // These are created in the constructor and should not be disposed on every pipeline change
  76394. if (disposeNonRecreated) {
  76395. if (this.sharpen) {
  76396. this.sharpen.dispose(camera);
  76397. }
  76398. if (this.depthOfField) {
  76399. this.depthOfField.disposeEffects(camera);
  76400. }
  76401. if (this.bloom) {
  76402. this.bloom.disposeEffects(camera);
  76403. }
  76404. if (this.chromaticAberration) {
  76405. this.chromaticAberration.dispose(camera);
  76406. }
  76407. if (this.grain) {
  76408. this.grain.dispose(camera);
  76409. }
  76410. if (this._glowLayer) {
  76411. this._glowLayer.dispose();
  76412. }
  76413. }
  76414. }
  76415. this.imageProcessing = null;
  76416. this.fxaa = null;
  76417. if (disposeNonRecreated) {
  76418. this.sharpen = null;
  76419. this._sharpenEffect = null;
  76420. this.depthOfField = null;
  76421. this.bloom = null;
  76422. this.chromaticAberration = null;
  76423. this._chromaticAberrationEffect = null;
  76424. this.grain = null;
  76425. this._grainEffect = null;
  76426. this._glowLayer = null;
  76427. }
  76428. };
  76429. /**
  76430. * Adds a camera to the pipeline
  76431. * @param camera the camera to be added
  76432. */
  76433. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  76434. this._originalCameras.push(camera);
  76435. this._buildPipeline();
  76436. };
  76437. /**
  76438. * Removes a camera from the pipeline
  76439. * @param camera the camera to remove
  76440. */
  76441. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  76442. var index = this._originalCameras.indexOf(camera);
  76443. this._originalCameras.splice(index, 1);
  76444. this._buildPipeline();
  76445. };
  76446. /**
  76447. * Dispose of the pipeline and stop all post processes
  76448. */
  76449. DefaultRenderingPipeline.prototype.dispose = function () {
  76450. this._disposePostProcesses(true);
  76451. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76452. this._scene.autoClear = true;
  76453. if (this._resizeObserver) {
  76454. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76455. this._resizeObserver = null;
  76456. }
  76457. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76458. _super.prototype.dispose.call(this);
  76459. };
  76460. /**
  76461. * Serialize the rendering pipeline (Used when exporting)
  76462. * @returns the serialized object
  76463. */
  76464. DefaultRenderingPipeline.prototype.serialize = function () {
  76465. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76466. serializationObject.customType = "DefaultRenderingPipeline";
  76467. return serializationObject;
  76468. };
  76469. /**
  76470. * Parse the serialized pipeline
  76471. * @param source Source pipeline.
  76472. * @param scene The scene to load the pipeline to.
  76473. * @param rootUrl The URL of the serialized pipeline.
  76474. * @returns An instantiated pipeline from the serialized object.
  76475. */
  76476. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76477. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76478. };
  76479. __decorate([
  76480. BABYLON.serialize()
  76481. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76482. __decorate([
  76483. BABYLON.serialize()
  76484. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76485. __decorate([
  76486. BABYLON.serialize()
  76487. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76488. __decorate([
  76489. BABYLON.serialize()
  76490. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76491. __decorate([
  76492. BABYLON.serialize()
  76493. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76494. __decorate([
  76495. BABYLON.serialize()
  76496. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76497. __decorate([
  76498. BABYLON.serialize()
  76499. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76500. __decorate([
  76501. BABYLON.serialize()
  76502. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76503. __decorate([
  76504. BABYLON.serialize()
  76505. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76506. __decorate([
  76507. BABYLON.serialize()
  76508. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76509. __decorate([
  76510. BABYLON.serialize()
  76511. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76512. __decorate([
  76513. BABYLON.serialize()
  76514. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76515. __decorate([
  76516. BABYLON.serialize()
  76517. ], DefaultRenderingPipeline.prototype, "samples", null);
  76518. __decorate([
  76519. BABYLON.serialize()
  76520. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76521. __decorate([
  76522. BABYLON.serialize()
  76523. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76524. __decorate([
  76525. BABYLON.serialize()
  76526. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76527. __decorate([
  76528. BABYLON.serialize()
  76529. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76530. return DefaultRenderingPipeline;
  76531. }(BABYLON.PostProcessRenderPipeline));
  76532. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76533. })(BABYLON || (BABYLON = {}));
  76534. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76535. var BABYLON;
  76536. (function (BABYLON) {
  76537. /**
  76538. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76539. */
  76540. var GeometryBufferRenderer = /** @class */ (function () {
  76541. /**
  76542. * Creates a new G Buffer for the scene
  76543. * @param scene The scene the buffer belongs to
  76544. * @param ratio How big is the buffer related to the main canvas.
  76545. */
  76546. function GeometryBufferRenderer(scene, ratio) {
  76547. if (ratio === void 0) { ratio = 1; }
  76548. this._enablePosition = false;
  76549. this._scene = scene;
  76550. this._ratio = ratio;
  76551. // Render target
  76552. this._createRenderTargets();
  76553. }
  76554. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76555. /**
  76556. * Set the render list (meshes to be rendered) used in the G buffer.
  76557. */
  76558. set: function (meshes) {
  76559. this._multiRenderTarget.renderList = meshes;
  76560. },
  76561. enumerable: true,
  76562. configurable: true
  76563. });
  76564. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76565. /**
  76566. * Gets wether or not G buffer are supported by the running hardware.
  76567. * This requires draw buffer supports
  76568. */
  76569. get: function () {
  76570. return this._multiRenderTarget.isSupported;
  76571. },
  76572. enumerable: true,
  76573. configurable: true
  76574. });
  76575. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76576. /**
  76577. * Gets wether or not position are enabled for the G buffer.
  76578. */
  76579. get: function () {
  76580. return this._enablePosition;
  76581. },
  76582. /**
  76583. * Sets wether or not position are enabled for the G buffer.
  76584. */
  76585. set: function (enable) {
  76586. this._enablePosition = enable;
  76587. this.dispose();
  76588. this._createRenderTargets();
  76589. },
  76590. enumerable: true,
  76591. configurable: true
  76592. });
  76593. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76594. /**
  76595. * Gets the scene associated with the buffer.
  76596. */
  76597. get: function () {
  76598. return this._scene;
  76599. },
  76600. enumerable: true,
  76601. configurable: true
  76602. });
  76603. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76604. /**
  76605. * Gets the ratio used by the buffer during its creation.
  76606. * How big is the buffer related to the main canvas.
  76607. */
  76608. get: function () {
  76609. return this._ratio;
  76610. },
  76611. enumerable: true,
  76612. configurable: true
  76613. });
  76614. /**
  76615. * Checks wether everything is ready to render a submesh to the G buffer.
  76616. * @param subMesh the submesh to check readiness for
  76617. * @param useInstances is the mesh drawn using instance or not
  76618. * @returns true if ready otherwise false
  76619. */
  76620. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76621. var material = subMesh.getMaterial();
  76622. if (material && material.disableDepthWrite) {
  76623. return false;
  76624. }
  76625. var defines = [];
  76626. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76627. var mesh = subMesh.getMesh();
  76628. // Alpha test
  76629. if (material && material.needAlphaTesting()) {
  76630. defines.push("#define ALPHATEST");
  76631. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76632. attribs.push(BABYLON.VertexBuffer.UVKind);
  76633. defines.push("#define UV1");
  76634. }
  76635. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76636. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76637. defines.push("#define UV2");
  76638. }
  76639. }
  76640. // Buffers
  76641. if (this._enablePosition) {
  76642. defines.push("#define POSITION");
  76643. }
  76644. // Bones
  76645. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76646. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76647. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76648. if (mesh.numBoneInfluencers > 4) {
  76649. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76650. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76651. }
  76652. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76653. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76654. }
  76655. else {
  76656. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76657. }
  76658. // Instances
  76659. if (useInstances) {
  76660. defines.push("#define INSTANCES");
  76661. attribs.push("world0");
  76662. attribs.push("world1");
  76663. attribs.push("world2");
  76664. attribs.push("world3");
  76665. }
  76666. // Get correct effect
  76667. var join = defines.join("\n");
  76668. if (this._cachedDefines !== join) {
  76669. this._cachedDefines = join;
  76670. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76671. }
  76672. return this._effect.isReady();
  76673. };
  76674. /**
  76675. * Gets the current underlying G Buffer.
  76676. * @returns the buffer
  76677. */
  76678. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76679. return this._multiRenderTarget;
  76680. };
  76681. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76682. /**
  76683. * Gets the number of samples used to render the buffer (anti aliasing).
  76684. */
  76685. get: function () {
  76686. return this._multiRenderTarget.samples;
  76687. },
  76688. /**
  76689. * Sets the number of samples used to render the buffer (anti aliasing).
  76690. */
  76691. set: function (value) {
  76692. this._multiRenderTarget.samples = value;
  76693. },
  76694. enumerable: true,
  76695. configurable: true
  76696. });
  76697. /**
  76698. * Disposes the renderer and frees up associated resources.
  76699. */
  76700. GeometryBufferRenderer.prototype.dispose = function () {
  76701. this.getGBuffer().dispose();
  76702. };
  76703. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76704. var _this = this;
  76705. var engine = this._scene.getEngine();
  76706. var count = this._enablePosition ? 3 : 2;
  76707. 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 });
  76708. if (!this.isSupported) {
  76709. return;
  76710. }
  76711. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76712. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76713. this._multiRenderTarget.refreshRate = 1;
  76714. this._multiRenderTarget.renderParticles = false;
  76715. this._multiRenderTarget.renderList = null;
  76716. // set default depth value to 1.0 (far away)
  76717. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76718. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76719. });
  76720. // Custom render function
  76721. var renderSubMesh = function (subMesh) {
  76722. var mesh = subMesh.getRenderingMesh();
  76723. var scene = _this._scene;
  76724. var engine = scene.getEngine();
  76725. var material = subMesh.getMaterial();
  76726. if (!material) {
  76727. return;
  76728. }
  76729. // Culling
  76730. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76731. // Managing instances
  76732. var batch = mesh._getInstancesRenderList(subMesh._id);
  76733. if (batch.mustReturn) {
  76734. return;
  76735. }
  76736. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76737. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76738. engine.enableEffect(_this._effect);
  76739. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76740. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76741. _this._effect.setMatrix("view", scene.getViewMatrix());
  76742. // Alpha test
  76743. if (material && material.needAlphaTesting()) {
  76744. var alphaTexture = material.getAlphaTestTexture();
  76745. if (alphaTexture) {
  76746. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76747. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76748. }
  76749. }
  76750. // Bones
  76751. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76752. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76753. }
  76754. // Draw
  76755. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76756. }
  76757. };
  76758. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76759. var index;
  76760. if (depthOnlySubMeshes.length) {
  76761. engine.setColorWrite(false);
  76762. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76763. renderSubMesh(depthOnlySubMeshes.data[index]);
  76764. }
  76765. engine.setColorWrite(true);
  76766. }
  76767. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76768. renderSubMesh(opaqueSubMeshes.data[index]);
  76769. }
  76770. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76771. renderSubMesh(alphaTestSubMeshes.data[index]);
  76772. }
  76773. };
  76774. };
  76775. return GeometryBufferRenderer;
  76776. }());
  76777. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76778. })(BABYLON || (BABYLON = {}));
  76779. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76780. var BABYLON;
  76781. (function (BABYLON) {
  76782. /**
  76783. * This groups together the common properties used for image processing either in direct forward pass
  76784. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76785. * or not.
  76786. */
  76787. var ImageProcessingConfiguration = /** @class */ (function () {
  76788. function ImageProcessingConfiguration() {
  76789. /**
  76790. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76791. */
  76792. this.colorCurves = new BABYLON.ColorCurves();
  76793. this._colorCurvesEnabled = false;
  76794. this._colorGradingEnabled = false;
  76795. this._colorGradingWithGreenDepth = true;
  76796. this._colorGradingBGR = true;
  76797. this._exposure = 1.0;
  76798. this._toneMappingEnabled = false;
  76799. this._contrast = 1.0;
  76800. /**
  76801. * Vignette stretch size.
  76802. */
  76803. this.vignetteStretch = 0;
  76804. /**
  76805. * Vignette centre X Offset.
  76806. */
  76807. this.vignetteCentreX = 0;
  76808. /**
  76809. * Vignette centre Y Offset.
  76810. */
  76811. this.vignetteCentreY = 0;
  76812. /**
  76813. * Vignette weight or intensity of the vignette effect.
  76814. */
  76815. this.vignetteWeight = 1.5;
  76816. /**
  76817. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76818. * if vignetteEnabled is set to true.
  76819. */
  76820. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76821. /**
  76822. * Camera field of view used by the Vignette effect.
  76823. */
  76824. this.vignetteCameraFov = 0.5;
  76825. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  76826. this._vignetteEnabled = false;
  76827. this._applyByPostProcess = false;
  76828. this._isEnabled = true;
  76829. /**
  76830. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  76831. */
  76832. this.onUpdateParameters = new BABYLON.Observable();
  76833. }
  76834. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  76835. /**
  76836. * Gets wether the color curves effect is enabled.
  76837. */
  76838. get: function () {
  76839. return this._colorCurvesEnabled;
  76840. },
  76841. /**
  76842. * Sets wether the color curves effect is enabled.
  76843. */
  76844. set: function (value) {
  76845. if (this._colorCurvesEnabled === value) {
  76846. return;
  76847. }
  76848. this._colorCurvesEnabled = value;
  76849. this._updateParameters();
  76850. },
  76851. enumerable: true,
  76852. configurable: true
  76853. });
  76854. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76855. /**
  76856. * Gets wether the color grading effect is enabled.
  76857. */
  76858. get: function () {
  76859. return this._colorGradingEnabled;
  76860. },
  76861. /**
  76862. * Sets wether the color grading effect is enabled.
  76863. */
  76864. set: function (value) {
  76865. if (this._colorGradingEnabled === value) {
  76866. return;
  76867. }
  76868. this._colorGradingEnabled = value;
  76869. this._updateParameters();
  76870. },
  76871. enumerable: true,
  76872. configurable: true
  76873. });
  76874. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76875. /**
  76876. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76877. */
  76878. get: function () {
  76879. return this._colorGradingWithGreenDepth;
  76880. },
  76881. /**
  76882. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76883. */
  76884. set: function (value) {
  76885. if (this._colorGradingWithGreenDepth === value) {
  76886. return;
  76887. }
  76888. this._colorGradingWithGreenDepth = value;
  76889. this._updateParameters();
  76890. },
  76891. enumerable: true,
  76892. configurable: true
  76893. });
  76894. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76895. /**
  76896. * Gets wether the color grading texture contains BGR values.
  76897. */
  76898. get: function () {
  76899. return this._colorGradingBGR;
  76900. },
  76901. /**
  76902. * Sets wether the color grading texture contains BGR values.
  76903. */
  76904. set: function (value) {
  76905. if (this._colorGradingBGR === value) {
  76906. return;
  76907. }
  76908. this._colorGradingBGR = value;
  76909. this._updateParameters();
  76910. },
  76911. enumerable: true,
  76912. configurable: true
  76913. });
  76914. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76915. /**
  76916. * Gets the Exposure used in the effect.
  76917. */
  76918. get: function () {
  76919. return this._exposure;
  76920. },
  76921. /**
  76922. * Sets the Exposure used in the effect.
  76923. */
  76924. set: function (value) {
  76925. if (this._exposure === value) {
  76926. return;
  76927. }
  76928. this._exposure = value;
  76929. this._updateParameters();
  76930. },
  76931. enumerable: true,
  76932. configurable: true
  76933. });
  76934. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76935. /**
  76936. * Gets wether the tone mapping effect is enabled.
  76937. */
  76938. get: function () {
  76939. return this._toneMappingEnabled;
  76940. },
  76941. /**
  76942. * Sets wether the tone mapping effect is enabled.
  76943. */
  76944. set: function (value) {
  76945. if (this._toneMappingEnabled === value) {
  76946. return;
  76947. }
  76948. this._toneMappingEnabled = value;
  76949. this._updateParameters();
  76950. },
  76951. enumerable: true,
  76952. configurable: true
  76953. });
  76954. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76955. /**
  76956. * Gets the contrast used in the effect.
  76957. */
  76958. get: function () {
  76959. return this._contrast;
  76960. },
  76961. /**
  76962. * Sets the contrast used in the effect.
  76963. */
  76964. set: function (value) {
  76965. if (this._contrast === value) {
  76966. return;
  76967. }
  76968. this._contrast = value;
  76969. this._updateParameters();
  76970. },
  76971. enumerable: true,
  76972. configurable: true
  76973. });
  76974. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76975. /**
  76976. * Gets the vignette blend mode allowing different kind of effect.
  76977. */
  76978. get: function () {
  76979. return this._vignetteBlendMode;
  76980. },
  76981. /**
  76982. * Sets the vignette blend mode allowing different kind of effect.
  76983. */
  76984. set: function (value) {
  76985. if (this._vignetteBlendMode === value) {
  76986. return;
  76987. }
  76988. this._vignetteBlendMode = value;
  76989. this._updateParameters();
  76990. },
  76991. enumerable: true,
  76992. configurable: true
  76993. });
  76994. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  76995. /**
  76996. * Gets wether the vignette effect is enabled.
  76997. */
  76998. get: function () {
  76999. return this._vignetteEnabled;
  77000. },
  77001. /**
  77002. * Sets wether the vignette effect is enabled.
  77003. */
  77004. set: function (value) {
  77005. if (this._vignetteEnabled === value) {
  77006. return;
  77007. }
  77008. this._vignetteEnabled = value;
  77009. this._updateParameters();
  77010. },
  77011. enumerable: true,
  77012. configurable: true
  77013. });
  77014. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77015. /**
  77016. * Gets wether the image processing is applied through a post process or not.
  77017. */
  77018. get: function () {
  77019. return this._applyByPostProcess;
  77020. },
  77021. /**
  77022. * Sets wether the image processing is applied through a post process or not.
  77023. */
  77024. set: function (value) {
  77025. if (this._applyByPostProcess === value) {
  77026. return;
  77027. }
  77028. this._applyByPostProcess = value;
  77029. this._updateParameters();
  77030. },
  77031. enumerable: true,
  77032. configurable: true
  77033. });
  77034. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77035. /**
  77036. * Gets wether the image processing is enabled or not.
  77037. */
  77038. get: function () {
  77039. return this._isEnabled;
  77040. },
  77041. /**
  77042. * Sets wether the image processing is enabled or not.
  77043. */
  77044. set: function (value) {
  77045. if (this._isEnabled === value) {
  77046. return;
  77047. }
  77048. this._isEnabled = value;
  77049. this._updateParameters();
  77050. },
  77051. enumerable: true,
  77052. configurable: true
  77053. });
  77054. /**
  77055. * Method called each time the image processing information changes requires to recompile the effect.
  77056. */
  77057. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77058. this.onUpdateParameters.notifyObservers(this);
  77059. };
  77060. ImageProcessingConfiguration.prototype.getClassName = function () {
  77061. return "ImageProcessingConfiguration";
  77062. };
  77063. /**
  77064. * Prepare the list of uniforms associated with the Image Processing effects.
  77065. * @param uniformsList The list of uniforms used in the effect
  77066. * @param defines the list of defines currently in use
  77067. */
  77068. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77069. if (defines.EXPOSURE) {
  77070. uniforms.push("exposureLinear");
  77071. }
  77072. if (defines.CONTRAST) {
  77073. uniforms.push("contrast");
  77074. }
  77075. if (defines.COLORGRADING) {
  77076. uniforms.push("colorTransformSettings");
  77077. }
  77078. if (defines.VIGNETTE) {
  77079. uniforms.push("vInverseScreenSize");
  77080. uniforms.push("vignetteSettings1");
  77081. uniforms.push("vignetteSettings2");
  77082. }
  77083. if (defines.COLORCURVES) {
  77084. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77085. }
  77086. };
  77087. /**
  77088. * Prepare the list of samplers associated with the Image Processing effects.
  77089. * @param uniformsList The list of uniforms used in the effect
  77090. * @param defines the list of defines currently in use
  77091. */
  77092. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77093. if (defines.COLORGRADING) {
  77094. samplersList.push("txColorTransform");
  77095. }
  77096. };
  77097. /**
  77098. * Prepare the list of defines associated to the shader.
  77099. * @param defines the list of defines to complete
  77100. */
  77101. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77102. if (forPostProcess === void 0) { forPostProcess = false; }
  77103. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77104. defines.VIGNETTE = false;
  77105. defines.TONEMAPPING = false;
  77106. defines.CONTRAST = false;
  77107. defines.EXPOSURE = false;
  77108. defines.COLORCURVES = false;
  77109. defines.COLORGRADING = false;
  77110. defines.COLORGRADING3D = false;
  77111. defines.IMAGEPROCESSING = false;
  77112. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77113. return;
  77114. }
  77115. defines.VIGNETTE = this.vignetteEnabled;
  77116. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77117. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77118. defines.TONEMAPPING = this.toneMappingEnabled;
  77119. defines.CONTRAST = (this.contrast !== 1.0);
  77120. defines.EXPOSURE = (this.exposure !== 1.0);
  77121. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77122. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77123. if (defines.COLORGRADING) {
  77124. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77125. }
  77126. else {
  77127. defines.COLORGRADING3D = false;
  77128. }
  77129. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77130. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77131. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77132. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77133. };
  77134. /**
  77135. * Returns true if all the image processing information are ready.
  77136. */
  77137. ImageProcessingConfiguration.prototype.isReady = function () {
  77138. // Color Grading texure can not be none blocking.
  77139. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77140. };
  77141. /**
  77142. * Binds the image processing to the shader.
  77143. * @param effect The effect to bind to
  77144. */
  77145. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77146. if (aspectRatio === void 0) { aspectRatio = 1; }
  77147. // Color Curves
  77148. if (this._colorCurvesEnabled && this.colorCurves) {
  77149. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77150. }
  77151. // Vignette
  77152. if (this._vignetteEnabled) {
  77153. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77154. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77155. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77156. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77157. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77158. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77159. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77160. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77161. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77162. var vignettePower = -2.0 * this.vignetteWeight;
  77163. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77164. }
  77165. // Exposure
  77166. effect.setFloat("exposureLinear", this.exposure);
  77167. // Contrast
  77168. effect.setFloat("contrast", this.contrast);
  77169. // Color transform settings
  77170. if (this.colorGradingTexture) {
  77171. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77172. var textureSize = this.colorGradingTexture.getSize().height;
  77173. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77174. 0.5 / textureSize, // textureOffset
  77175. textureSize, // textureSize
  77176. this.colorGradingTexture.level // weight
  77177. );
  77178. }
  77179. };
  77180. /**
  77181. * Clones the current image processing instance.
  77182. * @return The cloned image processing
  77183. */
  77184. ImageProcessingConfiguration.prototype.clone = function () {
  77185. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77186. };
  77187. /**
  77188. * Serializes the current image processing instance to a json representation.
  77189. * @return a JSON representation
  77190. */
  77191. ImageProcessingConfiguration.prototype.serialize = function () {
  77192. return BABYLON.SerializationHelper.Serialize(this);
  77193. };
  77194. /**
  77195. * Parses the image processing from a json representation.
  77196. * @param source the JSON source to parse
  77197. * @return The parsed image processing
  77198. */
  77199. ImageProcessingConfiguration.Parse = function (source) {
  77200. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77201. };
  77202. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77203. /**
  77204. * Used to apply the vignette as a mix with the pixel color.
  77205. */
  77206. get: function () {
  77207. return this._VIGNETTEMODE_MULTIPLY;
  77208. },
  77209. enumerable: true,
  77210. configurable: true
  77211. });
  77212. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77213. /**
  77214. * Used to apply the vignette as a replacement of the pixel color.
  77215. */
  77216. get: function () {
  77217. return this._VIGNETTEMODE_OPAQUE;
  77218. },
  77219. enumerable: true,
  77220. configurable: true
  77221. });
  77222. // Static constants associated to the image processing.
  77223. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77224. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77225. __decorate([
  77226. BABYLON.serializeAsColorCurves()
  77227. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77228. __decorate([
  77229. BABYLON.serialize()
  77230. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77231. __decorate([
  77232. BABYLON.serializeAsTexture()
  77233. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77234. __decorate([
  77235. BABYLON.serialize()
  77236. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77237. __decorate([
  77238. BABYLON.serialize()
  77239. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77240. __decorate([
  77241. BABYLON.serialize()
  77242. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77243. __decorate([
  77244. BABYLON.serialize()
  77245. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77246. __decorate([
  77247. BABYLON.serialize()
  77248. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77249. __decorate([
  77250. BABYLON.serialize()
  77251. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77252. __decorate([
  77253. BABYLON.serialize()
  77254. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77255. __decorate([
  77256. BABYLON.serialize()
  77257. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77258. __decorate([
  77259. BABYLON.serialize()
  77260. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77261. __decorate([
  77262. BABYLON.serialize()
  77263. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77264. __decorate([
  77265. BABYLON.serializeAsColor4()
  77266. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77267. __decorate([
  77268. BABYLON.serialize()
  77269. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77270. __decorate([
  77271. BABYLON.serialize()
  77272. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77273. __decorate([
  77274. BABYLON.serialize()
  77275. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77276. __decorate([
  77277. BABYLON.serialize()
  77278. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77279. __decorate([
  77280. BABYLON.serialize()
  77281. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77282. return ImageProcessingConfiguration;
  77283. }());
  77284. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77285. })(BABYLON || (BABYLON = {}));
  77286. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77287. var BABYLON;
  77288. (function (BABYLON) {
  77289. /**
  77290. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77291. * It can help converting any input color in a desired output one. This can then be used to create effects
  77292. * from sepia, black and white to sixties or futuristic rendering...
  77293. *
  77294. * The only supported format is currently 3dl.
  77295. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77296. */
  77297. var ColorGradingTexture = /** @class */ (function (_super) {
  77298. __extends(ColorGradingTexture, _super);
  77299. /**
  77300. * Instantiates a ColorGradingTexture from the following parameters.
  77301. *
  77302. * @param url The location of the color gradind data (currently only supporting 3dl)
  77303. * @param scene The scene the texture will be used in
  77304. */
  77305. function ColorGradingTexture(url, scene) {
  77306. var _this = _super.call(this, scene) || this;
  77307. if (!url) {
  77308. return _this;
  77309. }
  77310. _this._engine = scene.getEngine();
  77311. _this._textureMatrix = BABYLON.Matrix.Identity();
  77312. _this.name = url;
  77313. _this.url = url;
  77314. _this.hasAlpha = false;
  77315. _this.isCube = false;
  77316. _this.is3D = _this._engine.webGLVersion > 1;
  77317. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77318. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77319. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77320. _this.anisotropicFilteringLevel = 1;
  77321. _this._texture = _this._getFromCache(url, true);
  77322. if (!_this._texture) {
  77323. if (!scene.useDelayedTextureLoading) {
  77324. _this.loadTexture();
  77325. }
  77326. else {
  77327. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77328. }
  77329. }
  77330. return _this;
  77331. }
  77332. /**
  77333. * Returns the texture matrix used in most of the material.
  77334. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77335. */
  77336. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77337. return this._textureMatrix;
  77338. };
  77339. /**
  77340. * Occurs when the file being loaded is a .3dl LUT file.
  77341. */
  77342. ColorGradingTexture.prototype.load3dlTexture = function () {
  77343. var engine = this._engine;
  77344. var texture;
  77345. if (engine.webGLVersion === 1) {
  77346. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77347. }
  77348. else {
  77349. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77350. }
  77351. this._texture = texture;
  77352. var callback = function (text) {
  77353. if (typeof text !== "string") {
  77354. return;
  77355. }
  77356. var data = null;
  77357. var tempData = null;
  77358. var line;
  77359. var lines = text.split('\n');
  77360. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77361. var maxColor = 0;
  77362. for (var i = 0; i < lines.length; i++) {
  77363. line = lines[i];
  77364. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77365. continue;
  77366. if (line.indexOf('#') === 0)
  77367. continue;
  77368. var words = line.split(" ");
  77369. if (size === 0) {
  77370. // Number of space + one
  77371. size = words.length;
  77372. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77373. tempData = new Float32Array(size * size * size * 4);
  77374. continue;
  77375. }
  77376. if (size != 0) {
  77377. var r = Math.max(parseInt(words[0]), 0);
  77378. var g = Math.max(parseInt(words[1]), 0);
  77379. var b = Math.max(parseInt(words[2]), 0);
  77380. maxColor = Math.max(r, maxColor);
  77381. maxColor = Math.max(g, maxColor);
  77382. maxColor = Math.max(b, maxColor);
  77383. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77384. if (tempData) {
  77385. tempData[pixelStorageIndex + 0] = r;
  77386. tempData[pixelStorageIndex + 1] = g;
  77387. tempData[pixelStorageIndex + 2] = b;
  77388. }
  77389. pixelIndexSlice++;
  77390. if (pixelIndexSlice % size == 0) {
  77391. pixelIndexH++;
  77392. pixelIndexSlice = 0;
  77393. if (pixelIndexH % size == 0) {
  77394. pixelIndexW++;
  77395. pixelIndexH = 0;
  77396. }
  77397. }
  77398. }
  77399. }
  77400. if (tempData && data) {
  77401. for (var i = 0; i < tempData.length; i++) {
  77402. if (i > 0 && (i + 1) % 4 === 0) {
  77403. data[i] = 255;
  77404. }
  77405. else {
  77406. var value = tempData[i];
  77407. data[i] = (value / maxColor * 255);
  77408. }
  77409. }
  77410. }
  77411. if (texture.is3D) {
  77412. texture.updateSize(size, size, size);
  77413. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77414. }
  77415. else {
  77416. texture.updateSize(size * size, size);
  77417. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77418. }
  77419. };
  77420. var scene = this.getScene();
  77421. if (scene) {
  77422. scene._loadFile(this.url, callback);
  77423. }
  77424. else {
  77425. this._engine._loadFile(this.url, callback);
  77426. }
  77427. return this._texture;
  77428. };
  77429. /**
  77430. * Starts the loading process of the texture.
  77431. */
  77432. ColorGradingTexture.prototype.loadTexture = function () {
  77433. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77434. this.load3dlTexture();
  77435. }
  77436. };
  77437. /**
  77438. * Clones the color gradind texture.
  77439. */
  77440. ColorGradingTexture.prototype.clone = function () {
  77441. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77442. // Base texture
  77443. newTexture.level = this.level;
  77444. return newTexture;
  77445. };
  77446. /**
  77447. * Called during delayed load for textures.
  77448. */
  77449. ColorGradingTexture.prototype.delayLoad = function () {
  77450. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77451. return;
  77452. }
  77453. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77454. this._texture = this._getFromCache(this.url, true);
  77455. if (!this._texture) {
  77456. this.loadTexture();
  77457. }
  77458. };
  77459. /**
  77460. * Parses a color grading texture serialized by Babylon.
  77461. * @param parsedTexture The texture information being parsedTexture
  77462. * @param scene The scene to load the texture in
  77463. * @param rootUrl The root url of the data assets to load
  77464. * @return A color gradind texture
  77465. */
  77466. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77467. var texture = null;
  77468. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77469. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77470. texture.name = parsedTexture.name;
  77471. texture.level = parsedTexture.level;
  77472. }
  77473. return texture;
  77474. };
  77475. /**
  77476. * Serializes the LUT texture to json format.
  77477. */
  77478. ColorGradingTexture.prototype.serialize = function () {
  77479. if (!this.name) {
  77480. return null;
  77481. }
  77482. var serializationObject = {};
  77483. serializationObject.name = this.name;
  77484. serializationObject.level = this.level;
  77485. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77486. return serializationObject;
  77487. };
  77488. /**
  77489. * Empty line regex stored for GC.
  77490. */
  77491. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77492. return ColorGradingTexture;
  77493. }(BABYLON.BaseTexture));
  77494. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77495. })(BABYLON || (BABYLON = {}));
  77496. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77497. var BABYLON;
  77498. (function (BABYLON) {
  77499. /**
  77500. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77501. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77502. * 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;
  77503. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77504. */
  77505. var ColorCurves = /** @class */ (function () {
  77506. function ColorCurves() {
  77507. this._dirty = true;
  77508. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77509. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77510. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77511. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77512. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77513. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77514. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77515. this._globalHue = 30;
  77516. this._globalDensity = 0;
  77517. this._globalSaturation = 0;
  77518. this._globalExposure = 0;
  77519. this._highlightsHue = 30;
  77520. this._highlightsDensity = 0;
  77521. this._highlightsSaturation = 0;
  77522. this._highlightsExposure = 0;
  77523. this._midtonesHue = 30;
  77524. this._midtonesDensity = 0;
  77525. this._midtonesSaturation = 0;
  77526. this._midtonesExposure = 0;
  77527. this._shadowsHue = 30;
  77528. this._shadowsDensity = 0;
  77529. this._shadowsSaturation = 0;
  77530. this._shadowsExposure = 0;
  77531. }
  77532. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77533. /**
  77534. * Gets the global Hue value.
  77535. * 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).
  77536. */
  77537. get: function () {
  77538. return this._globalHue;
  77539. },
  77540. /**
  77541. * Sets the global Hue value.
  77542. * 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).
  77543. */
  77544. set: function (value) {
  77545. this._globalHue = value;
  77546. this._dirty = true;
  77547. },
  77548. enumerable: true,
  77549. configurable: true
  77550. });
  77551. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77552. /**
  77553. * Gets the global Density value.
  77554. * 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.
  77555. * Values less than zero provide a filter of opposite hue.
  77556. */
  77557. get: function () {
  77558. return this._globalDensity;
  77559. },
  77560. /**
  77561. * Sets the global Density value.
  77562. * 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.
  77563. * Values less than zero provide a filter of opposite hue.
  77564. */
  77565. set: function (value) {
  77566. this._globalDensity = value;
  77567. this._dirty = true;
  77568. },
  77569. enumerable: true,
  77570. configurable: true
  77571. });
  77572. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77573. /**
  77574. * Gets the global Saturation value.
  77575. * 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.
  77576. */
  77577. get: function () {
  77578. return this._globalSaturation;
  77579. },
  77580. /**
  77581. * Sets the global Saturation value.
  77582. * 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.
  77583. */
  77584. set: function (value) {
  77585. this._globalSaturation = value;
  77586. this._dirty = true;
  77587. },
  77588. enumerable: true,
  77589. configurable: true
  77590. });
  77591. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77592. /**
  77593. * Gets the global Exposure value.
  77594. * 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.
  77595. */
  77596. get: function () {
  77597. return this._globalExposure;
  77598. },
  77599. /**
  77600. * Sets the global Exposure value.
  77601. * 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.
  77602. */
  77603. set: function (value) {
  77604. this._globalExposure = value;
  77605. this._dirty = true;
  77606. },
  77607. enumerable: true,
  77608. configurable: true
  77609. });
  77610. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77611. /**
  77612. * Gets the highlights Hue value.
  77613. * 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).
  77614. */
  77615. get: function () {
  77616. return this._highlightsHue;
  77617. },
  77618. /**
  77619. * Sets the highlights Hue value.
  77620. * 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).
  77621. */
  77622. set: function (value) {
  77623. this._highlightsHue = value;
  77624. this._dirty = true;
  77625. },
  77626. enumerable: true,
  77627. configurable: true
  77628. });
  77629. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77630. /**
  77631. * Gets the highlights Density value.
  77632. * 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.
  77633. * Values less than zero provide a filter of opposite hue.
  77634. */
  77635. get: function () {
  77636. return this._highlightsDensity;
  77637. },
  77638. /**
  77639. * Sets the highlights Density value.
  77640. * 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.
  77641. * Values less than zero provide a filter of opposite hue.
  77642. */
  77643. set: function (value) {
  77644. this._highlightsDensity = value;
  77645. this._dirty = true;
  77646. },
  77647. enumerable: true,
  77648. configurable: true
  77649. });
  77650. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77651. /**
  77652. * Gets the highlights Saturation value.
  77653. * 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.
  77654. */
  77655. get: function () {
  77656. return this._highlightsSaturation;
  77657. },
  77658. /**
  77659. * Sets the highlights Saturation value.
  77660. * 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.
  77661. */
  77662. set: function (value) {
  77663. this._highlightsSaturation = value;
  77664. this._dirty = true;
  77665. },
  77666. enumerable: true,
  77667. configurable: true
  77668. });
  77669. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77670. /**
  77671. * Gets the highlights Exposure value.
  77672. * 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.
  77673. */
  77674. get: function () {
  77675. return this._highlightsExposure;
  77676. },
  77677. /**
  77678. * Sets the highlights Exposure value.
  77679. * 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.
  77680. */
  77681. set: function (value) {
  77682. this._highlightsExposure = value;
  77683. this._dirty = true;
  77684. },
  77685. enumerable: true,
  77686. configurable: true
  77687. });
  77688. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77689. /**
  77690. * Gets the midtones Hue value.
  77691. * 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).
  77692. */
  77693. get: function () {
  77694. return this._midtonesHue;
  77695. },
  77696. /**
  77697. * Sets the midtones Hue value.
  77698. * 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).
  77699. */
  77700. set: function (value) {
  77701. this._midtonesHue = value;
  77702. this._dirty = true;
  77703. },
  77704. enumerable: true,
  77705. configurable: true
  77706. });
  77707. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  77708. /**
  77709. * Gets the midtones Density value.
  77710. * 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.
  77711. * Values less than zero provide a filter of opposite hue.
  77712. */
  77713. get: function () {
  77714. return this._midtonesDensity;
  77715. },
  77716. /**
  77717. * Sets the midtones Density value.
  77718. * 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.
  77719. * Values less than zero provide a filter of opposite hue.
  77720. */
  77721. set: function (value) {
  77722. this._midtonesDensity = value;
  77723. this._dirty = true;
  77724. },
  77725. enumerable: true,
  77726. configurable: true
  77727. });
  77728. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  77729. /**
  77730. * Gets the midtones Saturation value.
  77731. * 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.
  77732. */
  77733. get: function () {
  77734. return this._midtonesSaturation;
  77735. },
  77736. /**
  77737. * Sets the midtones Saturation value.
  77738. * 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.
  77739. */
  77740. set: function (value) {
  77741. this._midtonesSaturation = value;
  77742. this._dirty = true;
  77743. },
  77744. enumerable: true,
  77745. configurable: true
  77746. });
  77747. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  77748. /**
  77749. * Gets the midtones Exposure value.
  77750. * 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.
  77751. */
  77752. get: function () {
  77753. return this._midtonesExposure;
  77754. },
  77755. /**
  77756. * Sets the midtones Exposure value.
  77757. * 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.
  77758. */
  77759. set: function (value) {
  77760. this._midtonesExposure = value;
  77761. this._dirty = true;
  77762. },
  77763. enumerable: true,
  77764. configurable: true
  77765. });
  77766. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77767. /**
  77768. * Gets the shadows Hue value.
  77769. * 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).
  77770. */
  77771. get: function () {
  77772. return this._shadowsHue;
  77773. },
  77774. /**
  77775. * Sets the shadows Hue value.
  77776. * 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).
  77777. */
  77778. set: function (value) {
  77779. this._shadowsHue = value;
  77780. this._dirty = true;
  77781. },
  77782. enumerable: true,
  77783. configurable: true
  77784. });
  77785. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77786. /**
  77787. * Gets the shadows Density value.
  77788. * 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.
  77789. * Values less than zero provide a filter of opposite hue.
  77790. */
  77791. get: function () {
  77792. return this._shadowsDensity;
  77793. },
  77794. /**
  77795. * Sets the shadows Density value.
  77796. * 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.
  77797. * Values less than zero provide a filter of opposite hue.
  77798. */
  77799. set: function (value) {
  77800. this._shadowsDensity = value;
  77801. this._dirty = true;
  77802. },
  77803. enumerable: true,
  77804. configurable: true
  77805. });
  77806. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77807. /**
  77808. * Gets the shadows Saturation value.
  77809. * 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.
  77810. */
  77811. get: function () {
  77812. return this._shadowsSaturation;
  77813. },
  77814. /**
  77815. * Sets the shadows Saturation value.
  77816. * 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.
  77817. */
  77818. set: function (value) {
  77819. this._shadowsSaturation = value;
  77820. this._dirty = true;
  77821. },
  77822. enumerable: true,
  77823. configurable: true
  77824. });
  77825. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  77826. /**
  77827. * Gets the shadows Exposure value.
  77828. * 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.
  77829. */
  77830. get: function () {
  77831. return this._shadowsExposure;
  77832. },
  77833. /**
  77834. * Sets the shadows Exposure value.
  77835. * 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.
  77836. */
  77837. set: function (value) {
  77838. this._shadowsExposure = value;
  77839. this._dirty = true;
  77840. },
  77841. enumerable: true,
  77842. configurable: true
  77843. });
  77844. ColorCurves.prototype.getClassName = function () {
  77845. return "ColorCurves";
  77846. };
  77847. /**
  77848. * Binds the color curves to the shader.
  77849. * @param colorCurves The color curve to bind
  77850. * @param effect The effect to bind to
  77851. */
  77852. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77853. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77854. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77855. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77856. if (colorCurves._dirty) {
  77857. colorCurves._dirty = false;
  77858. // Fill in global info.
  77859. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77860. // Compute highlights info.
  77861. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77862. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77863. // Compute midtones info.
  77864. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77865. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77866. // Compute shadows info.
  77867. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77868. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77869. // Compute deltas (neutral is midtones).
  77870. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77871. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77872. }
  77873. if (effect) {
  77874. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77875. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77876. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77877. }
  77878. };
  77879. /**
  77880. * Prepare the list of uniforms associated with the ColorCurves effects.
  77881. * @param uniformsList The list of uniforms used in the effect
  77882. */
  77883. ColorCurves.PrepareUniforms = function (uniformsList) {
  77884. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77885. };
  77886. /**
  77887. * Returns color grading data based on a hue, density, saturation and exposure value.
  77888. * @param filterHue The hue of the color filter.
  77889. * @param filterDensity The density of the color filter.
  77890. * @param saturation The saturation.
  77891. * @param exposure The exposure.
  77892. * @param result The result data container.
  77893. */
  77894. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77895. if (hue == null) {
  77896. return;
  77897. }
  77898. hue = ColorCurves.clamp(hue, 0, 360);
  77899. density = ColorCurves.clamp(density, -100, 100);
  77900. saturation = ColorCurves.clamp(saturation, -100, 100);
  77901. exposure = ColorCurves.clamp(exposure, -100, 100);
  77902. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77903. // so that the maximum filter density is only 50% control. This provides fine control
  77904. // for small values and reasonable range.
  77905. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77906. density *= 0.5;
  77907. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77908. if (density < 0) {
  77909. density *= -1;
  77910. hue = (hue + 180) % 360;
  77911. }
  77912. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77913. result.scaleToRef(2, result);
  77914. result.a = 1 + 0.01 * saturation;
  77915. };
  77916. /**
  77917. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77918. * @param value The input slider value in range [-100,100].
  77919. * @returns Adjusted value.
  77920. */
  77921. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77922. value /= 100;
  77923. var x = Math.abs(value);
  77924. x = Math.pow(x, 2);
  77925. if (value < 0) {
  77926. x *= -1;
  77927. }
  77928. x *= 100;
  77929. return x;
  77930. };
  77931. /**
  77932. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77933. * @param hue The hue (H) input.
  77934. * @param saturation The saturation (S) input.
  77935. * @param brightness The brightness (B) input.
  77936. * @result An RGBA color represented as Vector4.
  77937. */
  77938. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77939. var h = ColorCurves.clamp(hue, 0, 360);
  77940. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77941. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77942. if (s === 0) {
  77943. result.r = v;
  77944. result.g = v;
  77945. result.b = v;
  77946. }
  77947. else {
  77948. // sector 0 to 5
  77949. h /= 60;
  77950. var i = Math.floor(h);
  77951. // fractional part of h
  77952. var f = h - i;
  77953. var p = v * (1 - s);
  77954. var q = v * (1 - s * f);
  77955. var t = v * (1 - s * (1 - f));
  77956. switch (i) {
  77957. case 0:
  77958. result.r = v;
  77959. result.g = t;
  77960. result.b = p;
  77961. break;
  77962. case 1:
  77963. result.r = q;
  77964. result.g = v;
  77965. result.b = p;
  77966. break;
  77967. case 2:
  77968. result.r = p;
  77969. result.g = v;
  77970. result.b = t;
  77971. break;
  77972. case 3:
  77973. result.r = p;
  77974. result.g = q;
  77975. result.b = v;
  77976. break;
  77977. case 4:
  77978. result.r = t;
  77979. result.g = p;
  77980. result.b = v;
  77981. break;
  77982. default: // case 5:
  77983. result.r = v;
  77984. result.g = p;
  77985. result.b = q;
  77986. break;
  77987. }
  77988. }
  77989. result.a = 1;
  77990. };
  77991. /**
  77992. * Returns a value clamped between min and max
  77993. * @param value The value to clamp
  77994. * @param min The minimum of value
  77995. * @param max The maximum of value
  77996. * @returns The clamped value.
  77997. */
  77998. ColorCurves.clamp = function (value, min, max) {
  77999. return Math.min(Math.max(value, min), max);
  78000. };
  78001. /**
  78002. * Clones the current color curve instance.
  78003. * @return The cloned curves
  78004. */
  78005. ColorCurves.prototype.clone = function () {
  78006. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78007. };
  78008. /**
  78009. * Serializes the current color curve instance to a json representation.
  78010. * @return a JSON representation
  78011. */
  78012. ColorCurves.prototype.serialize = function () {
  78013. return BABYLON.SerializationHelper.Serialize(this);
  78014. };
  78015. /**
  78016. * Parses the color curve from a json representation.
  78017. * @param source the JSON source to parse
  78018. * @return The parsed curves
  78019. */
  78020. ColorCurves.Parse = function (source) {
  78021. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78022. };
  78023. __decorate([
  78024. BABYLON.serialize()
  78025. ], ColorCurves.prototype, "_globalHue", void 0);
  78026. __decorate([
  78027. BABYLON.serialize()
  78028. ], ColorCurves.prototype, "_globalDensity", void 0);
  78029. __decorate([
  78030. BABYLON.serialize()
  78031. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78032. __decorate([
  78033. BABYLON.serialize()
  78034. ], ColorCurves.prototype, "_globalExposure", void 0);
  78035. __decorate([
  78036. BABYLON.serialize()
  78037. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78038. __decorate([
  78039. BABYLON.serialize()
  78040. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78041. __decorate([
  78042. BABYLON.serialize()
  78043. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78044. __decorate([
  78045. BABYLON.serialize()
  78046. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78047. __decorate([
  78048. BABYLON.serialize()
  78049. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78050. __decorate([
  78051. BABYLON.serialize()
  78052. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78053. __decorate([
  78054. BABYLON.serialize()
  78055. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78056. __decorate([
  78057. BABYLON.serialize()
  78058. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78059. return ColorCurves;
  78060. }());
  78061. BABYLON.ColorCurves = ColorCurves;
  78062. })(BABYLON || (BABYLON = {}));
  78063. //# sourceMappingURL=babylon.colorCurves.js.map
  78064. var BABYLON;
  78065. (function (BABYLON) {
  78066. var RefractionPostProcess = /** @class */ (function (_super) {
  78067. __extends(RefractionPostProcess, _super);
  78068. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78069. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78070. _this.color = color;
  78071. _this.depth = depth;
  78072. _this.colorLevel = colorLevel;
  78073. _this._ownRefractionTexture = true;
  78074. _this.onActivateObservable.add(function (cam) {
  78075. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78076. });
  78077. _this.onApplyObservable.add(function (effect) {
  78078. effect.setColor3("baseColor", _this.color);
  78079. effect.setFloat("depth", _this.depth);
  78080. effect.setFloat("colorLevel", _this.colorLevel);
  78081. effect.setTexture("refractionSampler", _this._refTexture);
  78082. });
  78083. return _this;
  78084. }
  78085. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78086. /**
  78087. * Gets or sets the refraction texture
  78088. * Please note that you are responsible for disposing the texture if you set it manually
  78089. */
  78090. get: function () {
  78091. return this._refTexture;
  78092. },
  78093. set: function (value) {
  78094. if (this._refTexture && this._ownRefractionTexture) {
  78095. this._refTexture.dispose();
  78096. }
  78097. this._refTexture = value;
  78098. this._ownRefractionTexture = false;
  78099. },
  78100. enumerable: true,
  78101. configurable: true
  78102. });
  78103. // Methods
  78104. RefractionPostProcess.prototype.dispose = function (camera) {
  78105. if (this._refTexture && this._ownRefractionTexture) {
  78106. this._refTexture.dispose();
  78107. this._refTexture = null;
  78108. }
  78109. _super.prototype.dispose.call(this, camera);
  78110. };
  78111. return RefractionPostProcess;
  78112. }(BABYLON.PostProcess));
  78113. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78114. })(BABYLON || (BABYLON = {}));
  78115. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78116. var BABYLON;
  78117. (function (BABYLON) {
  78118. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78119. __extends(BlackAndWhitePostProcess, _super);
  78120. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78121. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78122. _this.degree = 1;
  78123. _this.onApplyObservable.add(function (effect) {
  78124. effect.setFloat("degree", _this.degree);
  78125. });
  78126. return _this;
  78127. }
  78128. return BlackAndWhitePostProcess;
  78129. }(BABYLON.PostProcess));
  78130. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78131. })(BABYLON || (BABYLON = {}));
  78132. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78133. var BABYLON;
  78134. (function (BABYLON) {
  78135. /**
  78136. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78137. * input texture to perform effects such as edge detection or sharpening
  78138. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78139. */
  78140. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78141. __extends(ConvolutionPostProcess, _super);
  78142. /**
  78143. * Creates a new instance ConvolutionPostProcess
  78144. * @param name The name of the effect.
  78145. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78146. * @param options The required width/height ratio to downsize to before computing the render pass.
  78147. * @param camera The camera to apply the render pass to.
  78148. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78149. * @param engine The engine which the post process will be applied. (default: current engine)
  78150. * @param reusable If the post process can be reused on the same frame. (default: false)
  78151. * @param textureType Type of textures used when performing the post process. (default: 0)
  78152. */
  78153. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78154. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78155. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78156. _this.kernel = kernel;
  78157. _this.onApply = function (effect) {
  78158. effect.setFloat2("screenSize", _this.width, _this.height);
  78159. effect.setArray("kernel", _this.kernel);
  78160. };
  78161. return _this;
  78162. }
  78163. // Statics
  78164. /**
  78165. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78166. */
  78167. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78168. /**
  78169. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78170. */
  78171. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78172. /**
  78173. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78174. */
  78175. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78176. /**
  78177. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78178. */
  78179. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78180. /**
  78181. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78182. */
  78183. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78184. /**
  78185. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78186. */
  78187. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78188. return ConvolutionPostProcess;
  78189. }(BABYLON.PostProcess));
  78190. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78191. })(BABYLON || (BABYLON = {}));
  78192. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78193. var BABYLON;
  78194. (function (BABYLON) {
  78195. var FilterPostProcess = /** @class */ (function (_super) {
  78196. __extends(FilterPostProcess, _super);
  78197. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78198. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78199. _this.kernelMatrix = kernelMatrix;
  78200. _this.onApply = function (effect) {
  78201. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78202. };
  78203. return _this;
  78204. }
  78205. return FilterPostProcess;
  78206. }(BABYLON.PostProcess));
  78207. BABYLON.FilterPostProcess = FilterPostProcess;
  78208. })(BABYLON || (BABYLON = {}));
  78209. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78210. var BABYLON;
  78211. (function (BABYLON) {
  78212. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78213. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78214. __extends(VolumetricLightScatteringPostProcess, _super);
  78215. /**
  78216. * @constructor
  78217. * @param {string} name - The post-process name
  78218. * @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)
  78219. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78220. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78221. * @param {number} samples - The post-process quality, default 100
  78222. * @param {number} samplingMode - The post-process filtering mode
  78223. * @param {BABYLON.Engine} engine - The babylon engine
  78224. * @param {boolean} reusable - If the post-process is reusable
  78225. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78226. */
  78227. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78228. if (samples === void 0) { samples = 100; }
  78229. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78230. 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;
  78231. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78232. /**
  78233. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78234. */
  78235. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78236. /**
  78237. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78238. */
  78239. _this.useCustomMeshPosition = false;
  78240. /**
  78241. * If the post-process should inverse the light scattering direction
  78242. */
  78243. _this.invert = true;
  78244. /**
  78245. * Array containing the excluded meshes not rendered in the internal pass
  78246. */
  78247. _this.excludedMeshes = new Array();
  78248. /**
  78249. * Controls the overall intensity of the post-process
  78250. */
  78251. _this.exposure = 0.3;
  78252. /**
  78253. * Dissipates each sample's contribution in range [0, 1]
  78254. */
  78255. _this.decay = 0.96815;
  78256. /**
  78257. * Controls the overall intensity of each sample
  78258. */
  78259. _this.weight = 0.58767;
  78260. /**
  78261. * Controls the density of each sample
  78262. */
  78263. _this.density = 0.926;
  78264. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78265. engine = scene.getEngine();
  78266. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78267. // Configure mesh
  78268. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78269. // Configure
  78270. _this._createPass(scene, ratio.passRatio || ratio);
  78271. _this.onActivate = function (camera) {
  78272. if (!_this.isSupported) {
  78273. _this.dispose(camera);
  78274. }
  78275. _this.onActivate = null;
  78276. };
  78277. _this.onApplyObservable.add(function (effect) {
  78278. _this._updateMeshScreenCoordinates(scene);
  78279. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78280. effect.setFloat("exposure", _this.exposure);
  78281. effect.setFloat("decay", _this.decay);
  78282. effect.setFloat("weight", _this.weight);
  78283. effect.setFloat("density", _this.density);
  78284. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78285. });
  78286. return _this;
  78287. }
  78288. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78289. get: function () {
  78290. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78291. return false;
  78292. },
  78293. set: function (useDiffuseColor) {
  78294. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78295. },
  78296. enumerable: true,
  78297. configurable: true
  78298. });
  78299. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78300. return "VolumetricLightScatteringPostProcess";
  78301. };
  78302. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78303. var mesh = subMesh.getMesh();
  78304. // Render this.mesh as default
  78305. if (mesh === this.mesh && mesh.material) {
  78306. return mesh.material.isReady(mesh);
  78307. }
  78308. var defines = [];
  78309. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78310. var material = subMesh.getMaterial();
  78311. // Alpha test
  78312. if (material) {
  78313. if (material.needAlphaTesting()) {
  78314. defines.push("#define ALPHATEST");
  78315. }
  78316. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78317. attribs.push(BABYLON.VertexBuffer.UVKind);
  78318. defines.push("#define UV1");
  78319. }
  78320. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78321. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78322. defines.push("#define UV2");
  78323. }
  78324. }
  78325. // Bones
  78326. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78327. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78328. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78329. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78330. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78331. }
  78332. else {
  78333. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78334. }
  78335. // Instances
  78336. if (useInstances) {
  78337. defines.push("#define INSTANCES");
  78338. attribs.push("world0");
  78339. attribs.push("world1");
  78340. attribs.push("world2");
  78341. attribs.push("world3");
  78342. }
  78343. // Get correct effect
  78344. var join = defines.join("\n");
  78345. if (this._cachedDefines !== join) {
  78346. this._cachedDefines = join;
  78347. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78348. }
  78349. return this._volumetricLightScatteringPass.isReady();
  78350. };
  78351. /**
  78352. * Sets the new light position for light scattering effect
  78353. * @param {BABYLON.Vector3} The new custom light position
  78354. */
  78355. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78356. this.customMeshPosition = position;
  78357. };
  78358. /**
  78359. * Returns the light position for light scattering effect
  78360. * @return {BABYLON.Vector3} The custom light position
  78361. */
  78362. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78363. return this.customMeshPosition;
  78364. };
  78365. /**
  78366. * Disposes the internal assets and detaches the post-process from the camera
  78367. */
  78368. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78369. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78370. if (rttIndex !== -1) {
  78371. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78372. }
  78373. this._volumetricLightScatteringRTT.dispose();
  78374. _super.prototype.dispose.call(this, camera);
  78375. };
  78376. /**
  78377. * Returns the render target texture used by the post-process
  78378. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78379. */
  78380. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78381. return this._volumetricLightScatteringRTT;
  78382. };
  78383. // Private methods
  78384. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78385. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78386. return true;
  78387. }
  78388. return false;
  78389. };
  78390. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78391. var _this = this;
  78392. var engine = scene.getEngine();
  78393. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78394. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78395. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78396. this._volumetricLightScatteringRTT.renderList = null;
  78397. this._volumetricLightScatteringRTT.renderParticles = false;
  78398. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78399. var camera = this.getCamera();
  78400. if (camera) {
  78401. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78402. }
  78403. else {
  78404. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78405. }
  78406. // Custom render function for submeshes
  78407. var renderSubMesh = function (subMesh) {
  78408. var mesh = subMesh.getRenderingMesh();
  78409. if (_this._meshExcluded(mesh)) {
  78410. return;
  78411. }
  78412. var material = subMesh.getMaterial();
  78413. if (!material) {
  78414. return;
  78415. }
  78416. var scene = mesh.getScene();
  78417. var engine = scene.getEngine();
  78418. // Culling
  78419. engine.setState(material.backFaceCulling);
  78420. // Managing instances
  78421. var batch = mesh._getInstancesRenderList(subMesh._id);
  78422. if (batch.mustReturn) {
  78423. return;
  78424. }
  78425. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78426. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78427. var effect = _this._volumetricLightScatteringPass;
  78428. if (mesh === _this.mesh) {
  78429. if (subMesh.effect) {
  78430. effect = subMesh.effect;
  78431. }
  78432. else {
  78433. effect = material.getEffect();
  78434. }
  78435. }
  78436. engine.enableEffect(effect);
  78437. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78438. if (mesh === _this.mesh) {
  78439. material.bind(mesh.getWorldMatrix(), mesh);
  78440. }
  78441. else {
  78442. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78443. // Alpha test
  78444. if (material && material.needAlphaTesting()) {
  78445. var alphaTexture = material.getAlphaTestTexture();
  78446. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78447. if (alphaTexture) {
  78448. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78449. }
  78450. }
  78451. // Bones
  78452. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78453. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78454. }
  78455. }
  78456. // Draw
  78457. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78458. }
  78459. };
  78460. // Render target texture callbacks
  78461. var savedSceneClearColor;
  78462. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78463. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78464. savedSceneClearColor = scene.clearColor;
  78465. scene.clearColor = sceneClearColor;
  78466. });
  78467. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78468. scene.clearColor = savedSceneClearColor;
  78469. });
  78470. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78471. var engine = scene.getEngine();
  78472. var index;
  78473. if (depthOnlySubMeshes.length) {
  78474. engine.setColorWrite(false);
  78475. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78476. renderSubMesh(depthOnlySubMeshes.data[index]);
  78477. }
  78478. engine.setColorWrite(true);
  78479. }
  78480. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78481. renderSubMesh(opaqueSubMeshes.data[index]);
  78482. }
  78483. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78484. renderSubMesh(alphaTestSubMeshes.data[index]);
  78485. }
  78486. if (transparentSubMeshes.length) {
  78487. // Sort sub meshes
  78488. for (index = 0; index < transparentSubMeshes.length; index++) {
  78489. var submesh = transparentSubMeshes.data[index];
  78490. var boundingInfo = submesh.getBoundingInfo();
  78491. if (boundingInfo && scene.activeCamera) {
  78492. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78493. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78494. }
  78495. }
  78496. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78497. sortedArray.sort(function (a, b) {
  78498. // Alpha index first
  78499. if (a._alphaIndex > b._alphaIndex) {
  78500. return 1;
  78501. }
  78502. if (a._alphaIndex < b._alphaIndex) {
  78503. return -1;
  78504. }
  78505. // Then distance to camera
  78506. if (a._distanceToCamera < b._distanceToCamera) {
  78507. return 1;
  78508. }
  78509. if (a._distanceToCamera > b._distanceToCamera) {
  78510. return -1;
  78511. }
  78512. return 0;
  78513. });
  78514. // Render sub meshes
  78515. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78516. for (index = 0; index < sortedArray.length; index++) {
  78517. renderSubMesh(sortedArray[index]);
  78518. }
  78519. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78520. }
  78521. };
  78522. };
  78523. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78524. var transform = scene.getTransformMatrix();
  78525. var meshPosition;
  78526. if (this.useCustomMeshPosition) {
  78527. meshPosition = this.customMeshPosition;
  78528. }
  78529. else if (this.attachedNode) {
  78530. meshPosition = this.attachedNode.position;
  78531. }
  78532. else {
  78533. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78534. }
  78535. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78536. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78537. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78538. if (this.invert)
  78539. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78540. };
  78541. // Static methods
  78542. /**
  78543. * Creates a default mesh for the Volumeric Light Scattering post-process
  78544. * @param {string} The mesh name
  78545. * @param {BABYLON.Scene} The scene where to create the mesh
  78546. * @return {BABYLON.Mesh} the default mesh
  78547. */
  78548. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78549. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78550. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78551. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78552. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78553. mesh.material = material;
  78554. return mesh;
  78555. };
  78556. __decorate([
  78557. BABYLON.serializeAsVector3()
  78558. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78559. __decorate([
  78560. BABYLON.serialize()
  78561. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78562. __decorate([
  78563. BABYLON.serialize()
  78564. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78565. __decorate([
  78566. BABYLON.serializeAsMeshReference()
  78567. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78568. __decorate([
  78569. BABYLON.serialize()
  78570. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78571. __decorate([
  78572. BABYLON.serialize()
  78573. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78574. __decorate([
  78575. BABYLON.serialize()
  78576. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78577. __decorate([
  78578. BABYLON.serialize()
  78579. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78580. __decorate([
  78581. BABYLON.serialize()
  78582. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78583. return VolumetricLightScatteringPostProcess;
  78584. }(BABYLON.PostProcess));
  78585. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78586. })(BABYLON || (BABYLON = {}));
  78587. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78588. //
  78589. // This post-process allows the modification of rendered colors by using
  78590. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78591. //
  78592. // The object needs to be provided an url to a texture containing the color
  78593. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78594. // Use an image editing software to tweak the LUT to match your needs.
  78595. //
  78596. // For an example of a color LUT, see here:
  78597. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78598. // For explanations on color grading, see here:
  78599. // http://udn.epicgames.com/Three/ColorGrading.html
  78600. //
  78601. var BABYLON;
  78602. (function (BABYLON) {
  78603. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78604. __extends(ColorCorrectionPostProcess, _super);
  78605. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78606. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78607. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78608. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78609. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78610. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78611. _this.onApply = function (effect) {
  78612. effect.setTexture("colorTable", _this._colorTableTexture);
  78613. };
  78614. return _this;
  78615. }
  78616. return ColorCorrectionPostProcess;
  78617. }(BABYLON.PostProcess));
  78618. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78619. })(BABYLON || (BABYLON = {}));
  78620. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78621. var BABYLON;
  78622. (function (BABYLON) {
  78623. /** Defines operator used for tonemapping */
  78624. var TonemappingOperator;
  78625. (function (TonemappingOperator) {
  78626. /** Hable */
  78627. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78628. /** Reinhard */
  78629. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78630. /** HejiDawson */
  78631. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78632. /** Photographic */
  78633. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78634. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78635. ;
  78636. /**
  78637. * Defines a post process to apply tone mapping
  78638. */
  78639. var TonemapPostProcess = /** @class */ (function (_super) {
  78640. __extends(TonemapPostProcess, _super);
  78641. /**
  78642. * Creates a new TonemapPostProcess
  78643. * @param name defines the name of the postprocess
  78644. * @param _operator defines the operator to use
  78645. * @param exposureAdjustment defines the required exposure adjustement
  78646. * @param camera defines the camera to use (can be null)
  78647. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78648. * @param engine defines the hosting engine (can be ignore if camera is set)
  78649. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78650. */
  78651. function TonemapPostProcess(name, _operator,
  78652. /** Defines the required exposure adjustement */
  78653. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78654. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78655. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78656. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78657. _this._operator = _operator;
  78658. _this.exposureAdjustment = exposureAdjustment;
  78659. var defines = "#define ";
  78660. if (_this._operator === TonemappingOperator.Hable)
  78661. defines += "HABLE_TONEMAPPING";
  78662. else if (_this._operator === TonemappingOperator.Reinhard)
  78663. defines += "REINHARD_TONEMAPPING";
  78664. else if (_this._operator === TonemappingOperator.HejiDawson)
  78665. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78666. else if (_this._operator === TonemappingOperator.Photographic)
  78667. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78668. //sadly a second call to create the effect.
  78669. _this.updateEffect(defines);
  78670. _this.onApply = function (effect) {
  78671. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78672. };
  78673. return _this;
  78674. }
  78675. return TonemapPostProcess;
  78676. }(BABYLON.PostProcess));
  78677. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78678. })(BABYLON || (BABYLON = {}));
  78679. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78680. var BABYLON;
  78681. (function (BABYLON) {
  78682. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78683. __extends(DisplayPassPostProcess, _super);
  78684. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78685. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78686. }
  78687. return DisplayPassPostProcess;
  78688. }(BABYLON.PostProcess));
  78689. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  78690. })(BABYLON || (BABYLON = {}));
  78691. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  78692. var BABYLON;
  78693. (function (BABYLON) {
  78694. var HighlightsPostProcess = /** @class */ (function (_super) {
  78695. __extends(HighlightsPostProcess, _super);
  78696. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78697. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78698. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78699. }
  78700. return HighlightsPostProcess;
  78701. }(BABYLON.PostProcess));
  78702. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  78703. })(BABYLON || (BABYLON = {}));
  78704. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  78705. var BABYLON;
  78706. (function (BABYLON) {
  78707. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  78708. __extends(ImageProcessingPostProcess, _super);
  78709. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  78710. if (camera === void 0) { camera = null; }
  78711. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78712. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  78713. _this._fromLinearSpace = true;
  78714. /**
  78715. * Defines cache preventing GC.
  78716. */
  78717. _this._defines = {
  78718. IMAGEPROCESSING: false,
  78719. VIGNETTE: false,
  78720. VIGNETTEBLENDMODEMULTIPLY: false,
  78721. VIGNETTEBLENDMODEOPAQUE: false,
  78722. TONEMAPPING: false,
  78723. CONTRAST: false,
  78724. COLORCURVES: false,
  78725. COLORGRADING: false,
  78726. COLORGRADING3D: false,
  78727. FROMLINEARSPACE: false,
  78728. SAMPLER3DGREENDEPTH: false,
  78729. SAMPLER3DBGRMAP: false,
  78730. IMAGEPROCESSINGPOSTPROCESS: false,
  78731. EXPOSURE: false,
  78732. };
  78733. // Setup the configuration as forced by the constructor. This would then not force the
  78734. // scene materials output in linear space and let untouched the default forward pass.
  78735. if (imageProcessingConfiguration) {
  78736. imageProcessingConfiguration.applyByPostProcess = true;
  78737. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  78738. // This will cause the shader to be compiled
  78739. _this.fromLinearSpace = false;
  78740. }
  78741. // Setup the default processing configuration to the scene.
  78742. else {
  78743. _this._attachImageProcessingConfiguration(null, true);
  78744. _this.imageProcessingConfiguration.applyByPostProcess = true;
  78745. }
  78746. _this.onApply = function (effect) {
  78747. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  78748. };
  78749. return _this;
  78750. }
  78751. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  78752. /**
  78753. * Gets the image processing configuration used either in this material.
  78754. */
  78755. get: function () {
  78756. return this._imageProcessingConfiguration;
  78757. },
  78758. /**
  78759. * Sets the Default image processing configuration used either in the this material.
  78760. *
  78761. * If sets to null, the scene one is in use.
  78762. */
  78763. set: function (value) {
  78764. this._attachImageProcessingConfiguration(value);
  78765. },
  78766. enumerable: true,
  78767. configurable: true
  78768. });
  78769. /**
  78770. * Attaches a new image processing configuration to the PBR Material.
  78771. * @param configuration
  78772. */
  78773. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78774. var _this = this;
  78775. if (doNotBuild === void 0) { doNotBuild = false; }
  78776. if (configuration === this._imageProcessingConfiguration) {
  78777. return;
  78778. }
  78779. // Detaches observer.
  78780. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78781. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78782. }
  78783. // Pick the scene configuration if needed.
  78784. if (!configuration) {
  78785. var scene = null;
  78786. var engine = this.getEngine();
  78787. var camera = this.getCamera();
  78788. if (camera) {
  78789. scene = camera.getScene();
  78790. }
  78791. else if (engine && engine.scenes) {
  78792. var scenes = engine.scenes;
  78793. scene = scenes[scenes.length - 1];
  78794. }
  78795. else {
  78796. scene = BABYLON.Engine.LastCreatedScene;
  78797. }
  78798. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78799. }
  78800. else {
  78801. this._imageProcessingConfiguration = configuration;
  78802. }
  78803. // Attaches observer.
  78804. if (this._imageProcessingConfiguration) {
  78805. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78806. _this._updateParameters();
  78807. });
  78808. }
  78809. // Ensure the effect will be rebuilt.
  78810. if (!doNotBuild) {
  78811. this._updateParameters();
  78812. }
  78813. };
  78814. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78815. /**
  78816. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78817. */
  78818. get: function () {
  78819. return this.imageProcessingConfiguration.colorCurves;
  78820. },
  78821. /**
  78822. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78823. */
  78824. set: function (value) {
  78825. this.imageProcessingConfiguration.colorCurves = value;
  78826. },
  78827. enumerable: true,
  78828. configurable: true
  78829. });
  78830. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78831. /**
  78832. * Gets wether the color curves effect is enabled.
  78833. */
  78834. get: function () {
  78835. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78836. },
  78837. /**
  78838. * Sets wether the color curves effect is enabled.
  78839. */
  78840. set: function (value) {
  78841. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78842. },
  78843. enumerable: true,
  78844. configurable: true
  78845. });
  78846. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78847. /**
  78848. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78849. */
  78850. get: function () {
  78851. return this.imageProcessingConfiguration.colorGradingTexture;
  78852. },
  78853. /**
  78854. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78855. */
  78856. set: function (value) {
  78857. this.imageProcessingConfiguration.colorGradingTexture = value;
  78858. },
  78859. enumerable: true,
  78860. configurable: true
  78861. });
  78862. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78863. /**
  78864. * Gets wether the color grading effect is enabled.
  78865. */
  78866. get: function () {
  78867. return this.imageProcessingConfiguration.colorGradingEnabled;
  78868. },
  78869. /**
  78870. * Gets wether the color grading effect is enabled.
  78871. */
  78872. set: function (value) {
  78873. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78874. },
  78875. enumerable: true,
  78876. configurable: true
  78877. });
  78878. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78879. /**
  78880. * Gets exposure used in the effect.
  78881. */
  78882. get: function () {
  78883. return this.imageProcessingConfiguration.exposure;
  78884. },
  78885. /**
  78886. * Sets exposure used in the effect.
  78887. */
  78888. set: function (value) {
  78889. this.imageProcessingConfiguration.exposure = value;
  78890. },
  78891. enumerable: true,
  78892. configurable: true
  78893. });
  78894. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78895. /**
  78896. * Gets wether tonemapping is enabled or not.
  78897. */
  78898. get: function () {
  78899. return this._imageProcessingConfiguration.toneMappingEnabled;
  78900. },
  78901. /**
  78902. * Sets wether tonemapping is enabled or not
  78903. */
  78904. set: function (value) {
  78905. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78906. },
  78907. enumerable: true,
  78908. configurable: true
  78909. });
  78910. ;
  78911. ;
  78912. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78913. /**
  78914. * Gets contrast used in the effect.
  78915. */
  78916. get: function () {
  78917. return this.imageProcessingConfiguration.contrast;
  78918. },
  78919. /**
  78920. * Sets contrast used in the effect.
  78921. */
  78922. set: function (value) {
  78923. this.imageProcessingConfiguration.contrast = value;
  78924. },
  78925. enumerable: true,
  78926. configurable: true
  78927. });
  78928. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78929. /**
  78930. * Gets Vignette stretch size.
  78931. */
  78932. get: function () {
  78933. return this.imageProcessingConfiguration.vignetteStretch;
  78934. },
  78935. /**
  78936. * Sets Vignette stretch size.
  78937. */
  78938. set: function (value) {
  78939. this.imageProcessingConfiguration.vignetteStretch = value;
  78940. },
  78941. enumerable: true,
  78942. configurable: true
  78943. });
  78944. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78945. /**
  78946. * Gets Vignette centre X Offset.
  78947. */
  78948. get: function () {
  78949. return this.imageProcessingConfiguration.vignetteCentreX;
  78950. },
  78951. /**
  78952. * Sets Vignette centre X Offset.
  78953. */
  78954. set: function (value) {
  78955. this.imageProcessingConfiguration.vignetteCentreX = value;
  78956. },
  78957. enumerable: true,
  78958. configurable: true
  78959. });
  78960. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78961. /**
  78962. * Gets Vignette centre Y Offset.
  78963. */
  78964. get: function () {
  78965. return this.imageProcessingConfiguration.vignetteCentreY;
  78966. },
  78967. /**
  78968. * Sets Vignette centre Y Offset.
  78969. */
  78970. set: function (value) {
  78971. this.imageProcessingConfiguration.vignetteCentreY = value;
  78972. },
  78973. enumerable: true,
  78974. configurable: true
  78975. });
  78976. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78977. /**
  78978. * Gets Vignette weight or intensity of the vignette effect.
  78979. */
  78980. get: function () {
  78981. return this.imageProcessingConfiguration.vignetteWeight;
  78982. },
  78983. /**
  78984. * Sets Vignette weight or intensity of the vignette effect.
  78985. */
  78986. set: function (value) {
  78987. this.imageProcessingConfiguration.vignetteWeight = value;
  78988. },
  78989. enumerable: true,
  78990. configurable: true
  78991. });
  78992. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78993. /**
  78994. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78995. * if vignetteEnabled is set to true.
  78996. */
  78997. get: function () {
  78998. return this.imageProcessingConfiguration.vignetteColor;
  78999. },
  79000. /**
  79001. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79002. * if vignetteEnabled is set to true.
  79003. */
  79004. set: function (value) {
  79005. this.imageProcessingConfiguration.vignetteColor = value;
  79006. },
  79007. enumerable: true,
  79008. configurable: true
  79009. });
  79010. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79011. /**
  79012. * Gets Camera field of view used by the Vignette effect.
  79013. */
  79014. get: function () {
  79015. return this.imageProcessingConfiguration.vignetteCameraFov;
  79016. },
  79017. /**
  79018. * Sets Camera field of view used by the Vignette effect.
  79019. */
  79020. set: function (value) {
  79021. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79022. },
  79023. enumerable: true,
  79024. configurable: true
  79025. });
  79026. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79027. /**
  79028. * Gets the vignette blend mode allowing different kind of effect.
  79029. */
  79030. get: function () {
  79031. return this.imageProcessingConfiguration.vignetteBlendMode;
  79032. },
  79033. /**
  79034. * Sets the vignette blend mode allowing different kind of effect.
  79035. */
  79036. set: function (value) {
  79037. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79038. },
  79039. enumerable: true,
  79040. configurable: true
  79041. });
  79042. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79043. /**
  79044. * Gets wether the vignette effect is enabled.
  79045. */
  79046. get: function () {
  79047. return this.imageProcessingConfiguration.vignetteEnabled;
  79048. },
  79049. /**
  79050. * Sets wether the vignette effect is enabled.
  79051. */
  79052. set: function (value) {
  79053. this.imageProcessingConfiguration.vignetteEnabled = value;
  79054. },
  79055. enumerable: true,
  79056. configurable: true
  79057. });
  79058. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79059. /**
  79060. * Gets wether the input of the processing is in Gamma or Linear Space.
  79061. */
  79062. get: function () {
  79063. return this._fromLinearSpace;
  79064. },
  79065. /**
  79066. * Sets wether the input of the processing is in Gamma or Linear Space.
  79067. */
  79068. set: function (value) {
  79069. if (this._fromLinearSpace === value) {
  79070. return;
  79071. }
  79072. this._fromLinearSpace = value;
  79073. this._updateParameters();
  79074. },
  79075. enumerable: true,
  79076. configurable: true
  79077. });
  79078. ImageProcessingPostProcess.prototype.getClassName = function () {
  79079. return "ImageProcessingPostProcess";
  79080. };
  79081. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79082. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79083. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79084. var defines = "";
  79085. for (var define in this._defines) {
  79086. if (this._defines[define]) {
  79087. defines += "#define " + define + ";\r\n";
  79088. }
  79089. }
  79090. var samplers = ["textureSampler"];
  79091. var uniforms = ["scale"];
  79092. if (BABYLON.ImageProcessingConfiguration) {
  79093. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79094. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79095. }
  79096. this.updateEffect(defines, uniforms, samplers);
  79097. };
  79098. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79099. _super.prototype.dispose.call(this, camera);
  79100. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79101. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79102. }
  79103. if (this._imageProcessingConfiguration) {
  79104. this.imageProcessingConfiguration.applyByPostProcess = false;
  79105. }
  79106. };
  79107. __decorate([
  79108. BABYLON.serialize()
  79109. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79110. return ImageProcessingPostProcess;
  79111. }(BABYLON.PostProcess));
  79112. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79113. })(BABYLON || (BABYLON = {}));
  79114. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79115. var BABYLON;
  79116. (function (BABYLON) {
  79117. /**
  79118. * Class used to store bone information
  79119. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79120. */
  79121. var Bone = /** @class */ (function (_super) {
  79122. __extends(Bone, _super);
  79123. /**
  79124. * Create a new bone
  79125. * @param name defines the bone name
  79126. * @param skeleton defines the parent skeleton
  79127. * @param parentBone defines the parent (can be null if the bone is the root)
  79128. * @param localMatrix defines the local matrix
  79129. * @param restPose defines the rest pose matrix
  79130. * @param baseMatrix defines the base matrix
  79131. * @param index defines index of the bone in the hiearchy
  79132. */
  79133. function Bone(
  79134. /**
  79135. * defines the bone name
  79136. */
  79137. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79138. if (parentBone === void 0) { parentBone = null; }
  79139. if (localMatrix === void 0) { localMatrix = null; }
  79140. if (restPose === void 0) { restPose = null; }
  79141. if (baseMatrix === void 0) { baseMatrix = null; }
  79142. if (index === void 0) { index = null; }
  79143. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79144. _this.name = name;
  79145. /**
  79146. * Gets the list of child bones
  79147. */
  79148. _this.children = new Array();
  79149. /** Gets the animations associated with this bone */
  79150. _this.animations = new Array();
  79151. /**
  79152. * @hidden Internal only
  79153. * Set this value to map this bone to a different index in the transform matrices
  79154. * Set this value to -1 to exclude the bone from the transform matrices
  79155. */
  79156. _this._index = null;
  79157. _this._absoluteTransform = new BABYLON.Matrix();
  79158. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79159. _this._scalingDeterminant = 1;
  79160. _this._worldTransform = new BABYLON.Matrix();
  79161. _this._needToDecompose = true;
  79162. _this._needToCompose = false;
  79163. _this._skeleton = skeleton;
  79164. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79165. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79166. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79167. _this._index = index;
  79168. skeleton.bones.push(_this);
  79169. _this.setParent(parentBone, false);
  79170. if (baseMatrix || localMatrix) {
  79171. _this._updateDifferenceMatrix();
  79172. }
  79173. return _this;
  79174. }
  79175. Object.defineProperty(Bone.prototype, "_matrix", {
  79176. /** @hidden */
  79177. get: function () {
  79178. this._compose();
  79179. return this._localMatrix;
  79180. },
  79181. /** @hidden */
  79182. set: function (value) {
  79183. this._localMatrix.copyFrom(value);
  79184. this._needToDecompose = true;
  79185. },
  79186. enumerable: true,
  79187. configurable: true
  79188. });
  79189. // Members
  79190. /**
  79191. * Gets the parent skeleton
  79192. * @returns a skeleton
  79193. */
  79194. Bone.prototype.getSkeleton = function () {
  79195. return this._skeleton;
  79196. };
  79197. /**
  79198. * Gets parent bone
  79199. * @returns a bone or null if the bone is the root of the bone hierarchy
  79200. */
  79201. Bone.prototype.getParent = function () {
  79202. return this._parent;
  79203. };
  79204. /**
  79205. * Sets the parent bone
  79206. * @param parent defines the parent (can be null if the bone is the root)
  79207. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79208. */
  79209. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79210. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79211. if (this._parent === parent) {
  79212. return;
  79213. }
  79214. if (this._parent) {
  79215. var index = this._parent.children.indexOf(this);
  79216. if (index !== -1) {
  79217. this._parent.children.splice(index, 1);
  79218. }
  79219. }
  79220. this._parent = parent;
  79221. if (this._parent) {
  79222. this._parent.children.push(this);
  79223. }
  79224. if (updateDifferenceMatrix) {
  79225. this._updateDifferenceMatrix();
  79226. }
  79227. this.markAsDirty();
  79228. };
  79229. /**
  79230. * Gets the local matrix
  79231. * @returns a matrix
  79232. */
  79233. Bone.prototype.getLocalMatrix = function () {
  79234. this._compose();
  79235. return this._localMatrix;
  79236. };
  79237. /**
  79238. * Gets the base matrix (initial matrix which remains unchanged)
  79239. * @returns a matrix
  79240. */
  79241. Bone.prototype.getBaseMatrix = function () {
  79242. return this._baseMatrix;
  79243. };
  79244. /**
  79245. * Gets the rest pose matrix
  79246. * @returns a matrix
  79247. */
  79248. Bone.prototype.getRestPose = function () {
  79249. return this._restPose;
  79250. };
  79251. /**
  79252. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79253. */
  79254. Bone.prototype.getWorldMatrix = function () {
  79255. return this._worldTransform;
  79256. };
  79257. /**
  79258. * Sets the local matrix to rest pose matrix
  79259. */
  79260. Bone.prototype.returnToRest = function () {
  79261. this.updateMatrix(this._restPose.clone());
  79262. };
  79263. /**
  79264. * Gets the inverse of the absolute transform matrix.
  79265. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79266. * @returns a matrix
  79267. */
  79268. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79269. return this._invertedAbsoluteTransform;
  79270. };
  79271. /**
  79272. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79273. * @returns a matrix
  79274. */
  79275. Bone.prototype.getAbsoluteTransform = function () {
  79276. return this._absoluteTransform;
  79277. };
  79278. Object.defineProperty(Bone.prototype, "position", {
  79279. // Properties (matches AbstractMesh properties)
  79280. /** Gets or sets current position (in local space) */
  79281. get: function () {
  79282. this._decompose();
  79283. return this._localPosition;
  79284. },
  79285. set: function (newPosition) {
  79286. this._decompose();
  79287. this._localPosition.copyFrom(newPosition);
  79288. this._markAsDirtyAndCompose();
  79289. },
  79290. enumerable: true,
  79291. configurable: true
  79292. });
  79293. Object.defineProperty(Bone.prototype, "rotation", {
  79294. /** Gets or sets current rotation (in local space) */
  79295. get: function () {
  79296. return this.getRotation();
  79297. },
  79298. set: function (newRotation) {
  79299. this.setRotation(newRotation);
  79300. },
  79301. enumerable: true,
  79302. configurable: true
  79303. });
  79304. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79305. /** Gets or sets current rotation quaternion (in local space) */
  79306. get: function () {
  79307. this._decompose();
  79308. return this._localRotation;
  79309. },
  79310. set: function (newRotation) {
  79311. this.setRotationQuaternion(newRotation);
  79312. },
  79313. enumerable: true,
  79314. configurable: true
  79315. });
  79316. Object.defineProperty(Bone.prototype, "scaling", {
  79317. /** Gets or sets current scaling (in local space) */
  79318. get: function () {
  79319. return this.getScale();
  79320. },
  79321. set: function (newScaling) {
  79322. this.setScale(newScaling);
  79323. },
  79324. enumerable: true,
  79325. configurable: true
  79326. });
  79327. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79328. /**
  79329. * Gets the animation properties override
  79330. */
  79331. get: function () {
  79332. return this._skeleton.animationPropertiesOverride;
  79333. },
  79334. enumerable: true,
  79335. configurable: true
  79336. });
  79337. // Methods
  79338. Bone.prototype._decompose = function () {
  79339. if (!this._needToDecompose) {
  79340. return;
  79341. }
  79342. this._needToDecompose = false;
  79343. if (!this._localScaling) {
  79344. this._localScaling = BABYLON.Vector3.Zero();
  79345. this._localRotation = BABYLON.Quaternion.Zero();
  79346. this._localPosition = BABYLON.Vector3.Zero();
  79347. }
  79348. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79349. };
  79350. Bone.prototype._compose = function () {
  79351. if (!this._needToCompose) {
  79352. return;
  79353. }
  79354. this._needToCompose = false;
  79355. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79356. };
  79357. /**
  79358. * Update the base and local matrices
  79359. * @param matrix defines the new base or local matrix
  79360. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79361. * @param updateLocalMatrix defines if the local matrix should be updated
  79362. */
  79363. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79364. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79365. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79366. this._baseMatrix.copyFrom(matrix);
  79367. if (updateDifferenceMatrix) {
  79368. this._updateDifferenceMatrix();
  79369. }
  79370. if (updateLocalMatrix) {
  79371. this._localMatrix.copyFrom(matrix);
  79372. this._markAsDirtyAndDecompose();
  79373. }
  79374. else {
  79375. this.markAsDirty();
  79376. }
  79377. };
  79378. /** @hidden */
  79379. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79380. if (updateChildren === void 0) { updateChildren = true; }
  79381. if (!rootMatrix) {
  79382. rootMatrix = this._baseMatrix;
  79383. }
  79384. if (this._parent) {
  79385. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79386. }
  79387. else {
  79388. this._absoluteTransform.copyFrom(rootMatrix);
  79389. }
  79390. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79391. if (updateChildren) {
  79392. for (var index = 0; index < this.children.length; index++) {
  79393. this.children[index]._updateDifferenceMatrix();
  79394. }
  79395. }
  79396. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79397. };
  79398. /**
  79399. * Flag the bone as dirty (Forcing it to update everything)
  79400. */
  79401. Bone.prototype.markAsDirty = function () {
  79402. this._currentRenderId++;
  79403. this._childRenderId++;
  79404. this._skeleton._markAsDirty();
  79405. };
  79406. Bone.prototype._markAsDirtyAndCompose = function () {
  79407. this.markAsDirty();
  79408. this._needToCompose = true;
  79409. };
  79410. Bone.prototype._markAsDirtyAndDecompose = function () {
  79411. this.markAsDirty();
  79412. this._needToDecompose = true;
  79413. };
  79414. /**
  79415. * Copy an animation range from another bone
  79416. * @param source defines the source bone
  79417. * @param rangeName defines the range name to copy
  79418. * @param frameOffset defines the frame offset
  79419. * @param rescaleAsRequired defines if rescaling must be applied if required
  79420. * @param skelDimensionsRatio defines the scaling ratio
  79421. * @returns true if operation was successful
  79422. */
  79423. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79424. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79425. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79426. // all animation may be coming from a library skeleton, so may need to create animation
  79427. if (this.animations.length === 0) {
  79428. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79429. this.animations[0].setKeys([]);
  79430. }
  79431. // get animation info / verify there is such a range from the source bone
  79432. var sourceRange = source.animations[0].getRange(rangeName);
  79433. if (!sourceRange) {
  79434. return false;
  79435. }
  79436. var from = sourceRange.from;
  79437. var to = sourceRange.to;
  79438. var sourceKeys = source.animations[0].getKeys();
  79439. // rescaling prep
  79440. var sourceBoneLength = source.length;
  79441. var sourceParent = source.getParent();
  79442. var parent = this.getParent();
  79443. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79444. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79445. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79446. var destKeys = this.animations[0].getKeys();
  79447. // loop vars declaration
  79448. var orig;
  79449. var origTranslation;
  79450. var mat;
  79451. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79452. orig = sourceKeys[key];
  79453. if (orig.frame >= from && orig.frame <= to) {
  79454. if (rescaleAsRequired) {
  79455. mat = orig.value.clone();
  79456. // scale based on parent ratio, when bone has parent
  79457. if (parentScalingReqd) {
  79458. origTranslation = mat.getTranslation();
  79459. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79460. // scale based on skeleton dimension ratio when root bone, and value is passed
  79461. }
  79462. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79463. origTranslation = mat.getTranslation();
  79464. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79465. // use original when root bone, and no data for skelDimensionsRatio
  79466. }
  79467. else {
  79468. mat = orig.value;
  79469. }
  79470. }
  79471. else {
  79472. mat = orig.value;
  79473. }
  79474. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79475. }
  79476. }
  79477. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79478. return true;
  79479. };
  79480. /**
  79481. * Translate the bone in local or world space
  79482. * @param vec The amount to translate the bone
  79483. * @param space The space that the translation is in
  79484. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79485. */
  79486. Bone.prototype.translate = function (vec, space, mesh) {
  79487. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79488. var lm = this.getLocalMatrix();
  79489. if (space == BABYLON.Space.LOCAL) {
  79490. lm.m[12] += vec.x;
  79491. lm.m[13] += vec.y;
  79492. lm.m[14] += vec.z;
  79493. }
  79494. else {
  79495. var wm = null;
  79496. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79497. if (mesh) {
  79498. wm = mesh.getWorldMatrix();
  79499. }
  79500. this._skeleton.computeAbsoluteTransforms();
  79501. var tmat = Bone._tmpMats[0];
  79502. var tvec = Bone._tmpVecs[0];
  79503. if (this._parent) {
  79504. if (mesh && wm) {
  79505. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79506. tmat.multiplyToRef(wm, tmat);
  79507. }
  79508. else {
  79509. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79510. }
  79511. }
  79512. tmat.m[12] = 0;
  79513. tmat.m[13] = 0;
  79514. tmat.m[14] = 0;
  79515. tmat.invert();
  79516. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79517. lm.m[12] += tvec.x;
  79518. lm.m[13] += tvec.y;
  79519. lm.m[14] += tvec.z;
  79520. }
  79521. this._markAsDirtyAndDecompose();
  79522. };
  79523. /**
  79524. * Set the postion of the bone in local or world space
  79525. * @param position The position to set the bone
  79526. * @param space The space that the position is in
  79527. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79528. */
  79529. Bone.prototype.setPosition = function (position, space, mesh) {
  79530. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79531. var lm = this.getLocalMatrix();
  79532. if (space == BABYLON.Space.LOCAL) {
  79533. lm.m[12] = position.x;
  79534. lm.m[13] = position.y;
  79535. lm.m[14] = position.z;
  79536. }
  79537. else {
  79538. var wm = null;
  79539. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79540. if (mesh) {
  79541. wm = mesh.getWorldMatrix();
  79542. }
  79543. this._skeleton.computeAbsoluteTransforms();
  79544. var tmat = Bone._tmpMats[0];
  79545. var vec = Bone._tmpVecs[0];
  79546. if (this._parent) {
  79547. if (mesh && wm) {
  79548. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79549. tmat.multiplyToRef(wm, tmat);
  79550. }
  79551. else {
  79552. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79553. }
  79554. }
  79555. tmat.invert();
  79556. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79557. lm.m[12] = vec.x;
  79558. lm.m[13] = vec.y;
  79559. lm.m[14] = vec.z;
  79560. }
  79561. this._markAsDirtyAndDecompose();
  79562. };
  79563. /**
  79564. * Set the absolute position of the bone (world space)
  79565. * @param position The position to set the bone
  79566. * @param mesh The mesh that this bone is attached to
  79567. */
  79568. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79569. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79570. };
  79571. /**
  79572. * Scale the bone on the x, y and z axes (in local space)
  79573. * @param x The amount to scale the bone on the x axis
  79574. * @param y The amount to scale the bone on the y axis
  79575. * @param z The amount to scale the bone on the z axis
  79576. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79577. */
  79578. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79579. if (scaleChildren === void 0) { scaleChildren = false; }
  79580. var locMat = this.getLocalMatrix();
  79581. // Apply new scaling on top of current local matrix
  79582. var scaleMat = Bone._tmpMats[0];
  79583. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79584. scaleMat.multiplyToRef(locMat, locMat);
  79585. // Invert scaling matrix and apply the inverse to all children
  79586. scaleMat.invert();
  79587. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79588. var child = _a[_i];
  79589. var cm = child.getLocalMatrix();
  79590. cm.multiplyToRef(scaleMat, cm);
  79591. cm.m[12] *= x;
  79592. cm.m[13] *= y;
  79593. cm.m[14] *= z;
  79594. child._markAsDirtyAndDecompose();
  79595. }
  79596. this._markAsDirtyAndDecompose();
  79597. if (scaleChildren) {
  79598. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79599. var child = _c[_b];
  79600. child.scale(x, y, z, scaleChildren);
  79601. }
  79602. }
  79603. };
  79604. /**
  79605. * Set the bone scaling in local space
  79606. * @param scale defines the scaling vector
  79607. */
  79608. Bone.prototype.setScale = function (scale) {
  79609. this._decompose();
  79610. this._localScaling.copyFrom(scale);
  79611. this._markAsDirtyAndCompose();
  79612. };
  79613. /**
  79614. * Gets the current scaling in local space
  79615. * @returns the current scaling vector
  79616. */
  79617. Bone.prototype.getScale = function () {
  79618. this._decompose();
  79619. return this._localScaling;
  79620. };
  79621. /**
  79622. * Gets the current scaling in local space and stores it in a target vector
  79623. * @param result defines the target vector
  79624. */
  79625. Bone.prototype.getScaleToRef = function (result) {
  79626. this._decompose();
  79627. result.copyFrom(this._localScaling);
  79628. };
  79629. /**
  79630. * Set the yaw, pitch, and roll of the bone in local or world space
  79631. * @param yaw The rotation of the bone on the y axis
  79632. * @param pitch The rotation of the bone on the x axis
  79633. * @param roll The rotation of the bone on the z axis
  79634. * @param space The space that the axes of rotation are in
  79635. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79636. */
  79637. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79638. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79639. if (space === BABYLON.Space.LOCAL) {
  79640. var quat = Bone._tmpQuat;
  79641. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79642. this.setRotationQuaternion(quat, space, mesh);
  79643. return;
  79644. }
  79645. var rotMatInv = Bone._tmpMats[0];
  79646. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79647. return;
  79648. }
  79649. var rotMat = Bone._tmpMats[1];
  79650. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79651. rotMatInv.multiplyToRef(rotMat, rotMat);
  79652. this._rotateWithMatrix(rotMat, space, mesh);
  79653. };
  79654. /**
  79655. * Add a rotation to the bone on an axis in local or world space
  79656. * @param axis The axis to rotate the bone on
  79657. * @param amount The amount to rotate the bone
  79658. * @param space The space that the axis is in
  79659. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79660. */
  79661. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79662. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79663. var rmat = Bone._tmpMats[0];
  79664. rmat.m[12] = 0;
  79665. rmat.m[13] = 0;
  79666. rmat.m[14] = 0;
  79667. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79668. this._rotateWithMatrix(rmat, space, mesh);
  79669. };
  79670. /**
  79671. * Set the rotation of the bone to a particular axis angle in local or world space
  79672. * @param axis The axis to rotate the bone on
  79673. * @param angle The angle that the bone should be rotated to
  79674. * @param space The space that the axis is in
  79675. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79676. */
  79677. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79678. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79679. if (space === BABYLON.Space.LOCAL) {
  79680. var quat = Bone._tmpQuat;
  79681. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79682. this.setRotationQuaternion(quat, space, mesh);
  79683. return;
  79684. }
  79685. var rotMatInv = Bone._tmpMats[0];
  79686. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79687. return;
  79688. }
  79689. var rotMat = Bone._tmpMats[1];
  79690. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  79691. rotMatInv.multiplyToRef(rotMat, rotMat);
  79692. this._rotateWithMatrix(rotMat, space, mesh);
  79693. };
  79694. /**
  79695. * Set the euler rotation of the bone in local of world space
  79696. * @param rotation The euler rotation that the bone should be set to
  79697. * @param space The space that the rotation is in
  79698. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79699. */
  79700. Bone.prototype.setRotation = function (rotation, space, mesh) {
  79701. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79702. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  79703. };
  79704. /**
  79705. * Set the quaternion rotation of the bone in local of world space
  79706. * @param quat The quaternion rotation that the bone should be set to
  79707. * @param space The space that the rotation is in
  79708. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79709. */
  79710. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  79711. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79712. if (space === BABYLON.Space.LOCAL) {
  79713. this._decompose();
  79714. this._localRotation.copyFrom(quat);
  79715. this._markAsDirtyAndCompose();
  79716. return;
  79717. }
  79718. var rotMatInv = Bone._tmpMats[0];
  79719. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79720. return;
  79721. }
  79722. var rotMat = Bone._tmpMats[1];
  79723. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  79724. rotMatInv.multiplyToRef(rotMat, rotMat);
  79725. this._rotateWithMatrix(rotMat, space, mesh);
  79726. };
  79727. /**
  79728. * Set the rotation matrix of the bone in local of world space
  79729. * @param rotMat The rotation matrix that the bone should be set to
  79730. * @param space The space that the rotation is in
  79731. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79732. */
  79733. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  79734. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79735. if (space === BABYLON.Space.LOCAL) {
  79736. var quat = Bone._tmpQuat;
  79737. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  79738. this.setRotationQuaternion(quat, space, mesh);
  79739. return;
  79740. }
  79741. var rotMatInv = Bone._tmpMats[0];
  79742. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79743. return;
  79744. }
  79745. var rotMat2 = Bone._tmpMats[1];
  79746. rotMat2.copyFrom(rotMat);
  79747. rotMatInv.multiplyToRef(rotMat, rotMat2);
  79748. this._rotateWithMatrix(rotMat2, space, mesh);
  79749. };
  79750. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  79751. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79752. var lmat = this.getLocalMatrix();
  79753. var lx = lmat.m[12];
  79754. var ly = lmat.m[13];
  79755. var lz = lmat.m[14];
  79756. var parent = this.getParent();
  79757. var parentScale = Bone._tmpMats[3];
  79758. var parentScaleInv = Bone._tmpMats[4];
  79759. if (parent && space == BABYLON.Space.WORLD) {
  79760. if (mesh) {
  79761. parentScale.copyFrom(mesh.getWorldMatrix());
  79762. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79763. }
  79764. else {
  79765. parentScale.copyFrom(parent.getAbsoluteTransform());
  79766. }
  79767. parentScaleInv.copyFrom(parentScale);
  79768. parentScaleInv.invert();
  79769. lmat.multiplyToRef(parentScale, lmat);
  79770. lmat.multiplyToRef(rmat, lmat);
  79771. lmat.multiplyToRef(parentScaleInv, lmat);
  79772. }
  79773. else {
  79774. if (space == BABYLON.Space.WORLD && mesh) {
  79775. parentScale.copyFrom(mesh.getWorldMatrix());
  79776. parentScaleInv.copyFrom(parentScale);
  79777. parentScaleInv.invert();
  79778. lmat.multiplyToRef(parentScale, lmat);
  79779. lmat.multiplyToRef(rmat, lmat);
  79780. lmat.multiplyToRef(parentScaleInv, lmat);
  79781. }
  79782. else {
  79783. lmat.multiplyToRef(rmat, lmat);
  79784. }
  79785. }
  79786. lmat.m[12] = lx;
  79787. lmat.m[13] = ly;
  79788. lmat.m[14] = lz;
  79789. this.computeAbsoluteTransforms();
  79790. this._markAsDirtyAndDecompose();
  79791. };
  79792. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79793. var scaleMatrix = Bone._tmpMats[2];
  79794. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79795. if (mesh) {
  79796. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79797. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79798. }
  79799. rotMatInv.invert();
  79800. if (isNaN(rotMatInv.m[0])) {
  79801. // Matrix failed to invert.
  79802. // This can happen if scale is zero for example.
  79803. return false;
  79804. }
  79805. scaleMatrix.m[0] *= this._scalingDeterminant;
  79806. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79807. return true;
  79808. };
  79809. /**
  79810. * Get the position of the bone in local or world space
  79811. * @param space The space that the returned position is in
  79812. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79813. * @returns The position of the bone
  79814. */
  79815. Bone.prototype.getPosition = function (space, mesh) {
  79816. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79817. if (mesh === void 0) { mesh = null; }
  79818. var pos = BABYLON.Vector3.Zero();
  79819. this.getPositionToRef(space, mesh, pos);
  79820. return pos;
  79821. };
  79822. /**
  79823. * Copy the position of the bone to a vector3 in local or world space
  79824. * @param space The space that the returned position is in
  79825. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79826. * @param result The vector3 to copy the position to
  79827. */
  79828. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79829. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79830. if (space == BABYLON.Space.LOCAL) {
  79831. var lm = this.getLocalMatrix();
  79832. result.x = lm.m[12];
  79833. result.y = lm.m[13];
  79834. result.z = lm.m[14];
  79835. }
  79836. else {
  79837. var wm = null;
  79838. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79839. if (mesh) {
  79840. wm = mesh.getWorldMatrix();
  79841. }
  79842. this._skeleton.computeAbsoluteTransforms();
  79843. var tmat = Bone._tmpMats[0];
  79844. if (mesh && wm) {
  79845. tmat.copyFrom(this.getAbsoluteTransform());
  79846. tmat.multiplyToRef(wm, tmat);
  79847. }
  79848. else {
  79849. tmat = this.getAbsoluteTransform();
  79850. }
  79851. result.x = tmat.m[12];
  79852. result.y = tmat.m[13];
  79853. result.z = tmat.m[14];
  79854. }
  79855. };
  79856. /**
  79857. * Get the absolute position of the bone (world space)
  79858. * @param mesh The mesh that this bone is attached to
  79859. * @returns The absolute position of the bone
  79860. */
  79861. Bone.prototype.getAbsolutePosition = function (mesh) {
  79862. if (mesh === void 0) { mesh = null; }
  79863. var pos = BABYLON.Vector3.Zero();
  79864. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79865. return pos;
  79866. };
  79867. /**
  79868. * Copy the absolute position of the bone (world space) to the result param
  79869. * @param mesh The mesh that this bone is attached to
  79870. * @param result The vector3 to copy the absolute position to
  79871. */
  79872. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79873. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79874. };
  79875. /**
  79876. * Compute the absolute transforms of this bone and its children
  79877. */
  79878. Bone.prototype.computeAbsoluteTransforms = function () {
  79879. this._compose();
  79880. if (this._parent) {
  79881. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79882. }
  79883. else {
  79884. this._absoluteTransform.copyFrom(this._localMatrix);
  79885. var poseMatrix = this._skeleton.getPoseMatrix();
  79886. if (poseMatrix) {
  79887. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79888. }
  79889. }
  79890. var children = this.children;
  79891. var len = children.length;
  79892. for (var i = 0; i < len; i++) {
  79893. children[i].computeAbsoluteTransforms();
  79894. }
  79895. };
  79896. /**
  79897. * Get the world direction from an axis that is in the local space of the bone
  79898. * @param localAxis The local direction that is used to compute the world direction
  79899. * @param mesh The mesh that this bone is attached to
  79900. * @returns The world direction
  79901. */
  79902. Bone.prototype.getDirection = function (localAxis, mesh) {
  79903. if (mesh === void 0) { mesh = null; }
  79904. var result = BABYLON.Vector3.Zero();
  79905. this.getDirectionToRef(localAxis, mesh, result);
  79906. return result;
  79907. };
  79908. /**
  79909. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79910. * @param localAxis The local direction that is used to compute the world direction
  79911. * @param mesh The mesh that this bone is attached to
  79912. * @param result The vector3 that the world direction will be copied to
  79913. */
  79914. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79915. if (mesh === void 0) { mesh = null; }
  79916. var wm = null;
  79917. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79918. if (mesh) {
  79919. wm = mesh.getWorldMatrix();
  79920. }
  79921. this._skeleton.computeAbsoluteTransforms();
  79922. var mat = Bone._tmpMats[0];
  79923. mat.copyFrom(this.getAbsoluteTransform());
  79924. if (mesh && wm) {
  79925. mat.multiplyToRef(wm, mat);
  79926. }
  79927. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79928. result.normalize();
  79929. };
  79930. /**
  79931. * Get the euler rotation of the bone in local or world space
  79932. * @param space The space that the rotation should be in
  79933. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79934. * @returns The euler rotation
  79935. */
  79936. Bone.prototype.getRotation = function (space, mesh) {
  79937. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79938. if (mesh === void 0) { mesh = null; }
  79939. var result = BABYLON.Vector3.Zero();
  79940. this.getRotationToRef(space, mesh, result);
  79941. return result;
  79942. };
  79943. /**
  79944. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79945. * @param space The space that the rotation should be in
  79946. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79947. * @param result The vector3 that the rotation should be copied to
  79948. */
  79949. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79950. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79951. if (mesh === void 0) { mesh = null; }
  79952. var quat = Bone._tmpQuat;
  79953. this.getRotationQuaternionToRef(space, mesh, quat);
  79954. quat.toEulerAnglesToRef(result);
  79955. };
  79956. /**
  79957. * Get the quaternion rotation of the bone in either local or world space
  79958. * @param space The space that the rotation should be in
  79959. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79960. * @returns The quaternion rotation
  79961. */
  79962. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79963. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79964. if (mesh === void 0) { mesh = null; }
  79965. var result = BABYLON.Quaternion.Identity();
  79966. this.getRotationQuaternionToRef(space, mesh, result);
  79967. return result;
  79968. };
  79969. /**
  79970. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79971. * @param space The space that the rotation should be in
  79972. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79973. * @param result The quaternion that the rotation should be copied to
  79974. */
  79975. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79976. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79977. if (mesh === void 0) { mesh = null; }
  79978. if (space == BABYLON.Space.LOCAL) {
  79979. this._decompose();
  79980. result.copyFrom(this._localRotation);
  79981. }
  79982. else {
  79983. var mat = Bone._tmpMats[0];
  79984. var amat = this.getAbsoluteTransform();
  79985. if (mesh) {
  79986. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79987. }
  79988. else {
  79989. mat.copyFrom(amat);
  79990. }
  79991. mat.m[0] *= this._scalingDeterminant;
  79992. mat.m[1] *= this._scalingDeterminant;
  79993. mat.m[2] *= this._scalingDeterminant;
  79994. mat.decompose(undefined, result, undefined);
  79995. }
  79996. };
  79997. /**
  79998. * Get the rotation matrix of the bone in local or world space
  79999. * @param space The space that the rotation should be in
  80000. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80001. * @returns The rotation matrix
  80002. */
  80003. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80004. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80005. var result = BABYLON.Matrix.Identity();
  80006. this.getRotationMatrixToRef(space, mesh, result);
  80007. return result;
  80008. };
  80009. /**
  80010. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80011. * @param space The space that the rotation should be in
  80012. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80013. * @param result The quaternion that the rotation should be copied to
  80014. */
  80015. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80016. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80017. if (space == BABYLON.Space.LOCAL) {
  80018. this.getLocalMatrix().getRotationMatrixToRef(result);
  80019. }
  80020. else {
  80021. var mat = Bone._tmpMats[0];
  80022. var amat = this.getAbsoluteTransform();
  80023. if (mesh) {
  80024. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80025. }
  80026. else {
  80027. mat.copyFrom(amat);
  80028. }
  80029. mat.m[0] *= this._scalingDeterminant;
  80030. mat.m[1] *= this._scalingDeterminant;
  80031. mat.m[2] *= this._scalingDeterminant;
  80032. mat.getRotationMatrixToRef(result);
  80033. }
  80034. };
  80035. /**
  80036. * Get the world position of a point that is in the local space of the bone
  80037. * @param position The local position
  80038. * @param mesh The mesh that this bone is attached to
  80039. * @returns The world position
  80040. */
  80041. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80042. if (mesh === void 0) { mesh = null; }
  80043. var result = BABYLON.Vector3.Zero();
  80044. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80045. return result;
  80046. };
  80047. /**
  80048. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80049. * @param position The local position
  80050. * @param mesh The mesh that this bone is attached to
  80051. * @param result The vector3 that the world position should be copied to
  80052. */
  80053. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80054. if (mesh === void 0) { mesh = null; }
  80055. var wm = null;
  80056. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80057. if (mesh) {
  80058. wm = mesh.getWorldMatrix();
  80059. }
  80060. this._skeleton.computeAbsoluteTransforms();
  80061. var tmat = Bone._tmpMats[0];
  80062. if (mesh && wm) {
  80063. tmat.copyFrom(this.getAbsoluteTransform());
  80064. tmat.multiplyToRef(wm, tmat);
  80065. }
  80066. else {
  80067. tmat = this.getAbsoluteTransform();
  80068. }
  80069. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80070. };
  80071. /**
  80072. * Get the local position of a point that is in world space
  80073. * @param position The world position
  80074. * @param mesh The mesh that this bone is attached to
  80075. * @returns The local position
  80076. */
  80077. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80078. if (mesh === void 0) { mesh = null; }
  80079. var result = BABYLON.Vector3.Zero();
  80080. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80081. return result;
  80082. };
  80083. /**
  80084. * Get the local position of a point that is in world space and copy it to the result param
  80085. * @param position The world position
  80086. * @param mesh The mesh that this bone is attached to
  80087. * @param result The vector3 that the local position should be copied to
  80088. */
  80089. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80090. if (mesh === void 0) { mesh = null; }
  80091. var wm = null;
  80092. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80093. if (mesh) {
  80094. wm = mesh.getWorldMatrix();
  80095. }
  80096. this._skeleton.computeAbsoluteTransforms();
  80097. var tmat = Bone._tmpMats[0];
  80098. tmat.copyFrom(this.getAbsoluteTransform());
  80099. if (mesh && wm) {
  80100. tmat.multiplyToRef(wm, tmat);
  80101. }
  80102. tmat.invert();
  80103. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80104. };
  80105. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80106. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80107. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80108. return Bone;
  80109. }(BABYLON.Node));
  80110. BABYLON.Bone = Bone;
  80111. })(BABYLON || (BABYLON = {}));
  80112. //# sourceMappingURL=babylon.bone.js.map
  80113. var BABYLON;
  80114. (function (BABYLON) {
  80115. /**
  80116. * Class used to apply inverse kinematics to bones
  80117. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80118. */
  80119. var BoneIKController = /** @class */ (function () {
  80120. /**
  80121. * Creates a new BoneIKController
  80122. * @param mesh defines the mesh to control
  80123. * @param bone defines the bone to control
  80124. * @param options defines options to set up the controller
  80125. */
  80126. function BoneIKController(mesh, bone, options) {
  80127. /**
  80128. * Gets or sets the target position
  80129. */
  80130. this.targetPosition = BABYLON.Vector3.Zero();
  80131. /**
  80132. * Gets or sets the pole target position
  80133. */
  80134. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80135. /**
  80136. * Gets or sets the pole target local offset
  80137. */
  80138. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80139. /**
  80140. * Gets or sets the pole angle
  80141. */
  80142. this.poleAngle = 0;
  80143. /**
  80144. * 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)
  80145. */
  80146. this.slerpAmount = 1;
  80147. this._bone1Quat = BABYLON.Quaternion.Identity();
  80148. this._bone1Mat = BABYLON.Matrix.Identity();
  80149. this._bone2Ang = Math.PI;
  80150. this._maxAngle = Math.PI;
  80151. this._rightHandedSystem = false;
  80152. this._bendAxis = BABYLON.Vector3.Right();
  80153. this._slerping = false;
  80154. this._adjustRoll = 0;
  80155. this._bone2 = bone;
  80156. this._bone1 = bone.getParent();
  80157. if (!this._bone1) {
  80158. return;
  80159. }
  80160. this.mesh = mesh;
  80161. var bonePos = bone.getPosition();
  80162. if (bone.getAbsoluteTransform().determinant() > 0) {
  80163. this._rightHandedSystem = true;
  80164. this._bendAxis.x = 0;
  80165. this._bendAxis.y = 0;
  80166. this._bendAxis.z = -1;
  80167. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80168. this._adjustRoll = Math.PI * .5;
  80169. this._bendAxis.z = 1;
  80170. }
  80171. }
  80172. if (this._bone1.length) {
  80173. var boneScale1 = this._bone1.getScale();
  80174. var boneScale2 = this._bone2.getScale();
  80175. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80176. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80177. }
  80178. else if (this._bone1.children[0]) {
  80179. mesh.computeWorldMatrix(true);
  80180. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80181. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80182. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80183. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80184. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80185. }
  80186. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80187. this.maxAngle = Math.PI;
  80188. if (options) {
  80189. if (options.targetMesh) {
  80190. this.targetMesh = options.targetMesh;
  80191. this.targetMesh.computeWorldMatrix(true);
  80192. }
  80193. if (options.poleTargetMesh) {
  80194. this.poleTargetMesh = options.poleTargetMesh;
  80195. this.poleTargetMesh.computeWorldMatrix(true);
  80196. }
  80197. else if (options.poleTargetBone) {
  80198. this.poleTargetBone = options.poleTargetBone;
  80199. }
  80200. else if (this._bone1.getParent()) {
  80201. this.poleTargetBone = this._bone1.getParent();
  80202. }
  80203. if (options.poleTargetLocalOffset) {
  80204. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80205. }
  80206. if (options.poleAngle) {
  80207. this.poleAngle = options.poleAngle;
  80208. }
  80209. if (options.bendAxis) {
  80210. this._bendAxis.copyFrom(options.bendAxis);
  80211. }
  80212. if (options.maxAngle) {
  80213. this.maxAngle = options.maxAngle;
  80214. }
  80215. if (options.slerpAmount) {
  80216. this.slerpAmount = options.slerpAmount;
  80217. }
  80218. }
  80219. }
  80220. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80221. /**
  80222. * Gets or sets maximum allowed angle
  80223. */
  80224. get: function () {
  80225. return this._maxAngle;
  80226. },
  80227. set: function (value) {
  80228. this._setMaxAngle(value);
  80229. },
  80230. enumerable: true,
  80231. configurable: true
  80232. });
  80233. BoneIKController.prototype._setMaxAngle = function (ang) {
  80234. if (ang < 0) {
  80235. ang = 0;
  80236. }
  80237. if (ang > Math.PI || ang == undefined) {
  80238. ang = Math.PI;
  80239. }
  80240. this._maxAngle = ang;
  80241. var a = this._bone1Length;
  80242. var b = this._bone2Length;
  80243. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80244. };
  80245. /**
  80246. * Force the controller to update the bones
  80247. */
  80248. BoneIKController.prototype.update = function () {
  80249. var bone1 = this._bone1;
  80250. if (!bone1) {
  80251. return;
  80252. }
  80253. var target = this.targetPosition;
  80254. var poleTarget = this.poleTargetPosition;
  80255. var mat1 = BoneIKController._tmpMats[0];
  80256. var mat2 = BoneIKController._tmpMats[1];
  80257. if (this.targetMesh) {
  80258. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80259. }
  80260. if (this.poleTargetBone) {
  80261. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80262. }
  80263. else if (this.poleTargetMesh) {
  80264. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80265. }
  80266. var bonePos = BoneIKController._tmpVecs[0];
  80267. var zaxis = BoneIKController._tmpVecs[1];
  80268. var xaxis = BoneIKController._tmpVecs[2];
  80269. var yaxis = BoneIKController._tmpVecs[3];
  80270. var upAxis = BoneIKController._tmpVecs[4];
  80271. var _tmpQuat = BoneIKController._tmpQuat;
  80272. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80273. poleTarget.subtractToRef(bonePos, upAxis);
  80274. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80275. upAxis.y = 1;
  80276. }
  80277. else {
  80278. upAxis.normalize();
  80279. }
  80280. target.subtractToRef(bonePos, yaxis);
  80281. yaxis.normalize();
  80282. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80283. zaxis.normalize();
  80284. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80285. xaxis.normalize();
  80286. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80287. var a = this._bone1Length;
  80288. var b = this._bone2Length;
  80289. var c = BABYLON.Vector3.Distance(bonePos, target);
  80290. if (this._maxReach > 0) {
  80291. c = Math.min(this._maxReach, c);
  80292. }
  80293. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80294. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80295. if (acosa > 1) {
  80296. acosa = 1;
  80297. }
  80298. if (acosb > 1) {
  80299. acosb = 1;
  80300. }
  80301. if (acosa < -1) {
  80302. acosa = -1;
  80303. }
  80304. if (acosb < -1) {
  80305. acosb = -1;
  80306. }
  80307. var angA = Math.acos(acosa);
  80308. var angB = Math.acos(acosb);
  80309. var angC = -angA - angB;
  80310. if (this._rightHandedSystem) {
  80311. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80312. mat2.multiplyToRef(mat1, mat1);
  80313. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80314. mat2.multiplyToRef(mat1, mat1);
  80315. }
  80316. else {
  80317. var _tmpVec = BoneIKController._tmpVecs[5];
  80318. _tmpVec.copyFrom(this._bendAxis);
  80319. _tmpVec.x *= -1;
  80320. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80321. mat2.multiplyToRef(mat1, mat1);
  80322. }
  80323. if (this.poleAngle) {
  80324. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80325. mat1.multiplyToRef(mat2, mat1);
  80326. }
  80327. if (this._bone1) {
  80328. if (this.slerpAmount < 1) {
  80329. if (!this._slerping) {
  80330. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80331. }
  80332. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80333. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80334. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80335. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80336. this._slerping = true;
  80337. }
  80338. else {
  80339. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80340. this._bone1Mat.copyFrom(mat1);
  80341. this._slerping = false;
  80342. }
  80343. }
  80344. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80345. this._bone2Ang = angC;
  80346. };
  80347. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80348. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80349. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80350. return BoneIKController;
  80351. }());
  80352. BABYLON.BoneIKController = BoneIKController;
  80353. })(BABYLON || (BABYLON = {}));
  80354. //# sourceMappingURL=babylon.boneIKController.js.map
  80355. var BABYLON;
  80356. (function (BABYLON) {
  80357. /**
  80358. * Class used to make a bone look toward a point in space
  80359. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80360. */
  80361. var BoneLookController = /** @class */ (function () {
  80362. /**
  80363. * Create a BoneLookController
  80364. * @param mesh the mesh that the bone belongs to
  80365. * @param bone the bone that will be looking to the target
  80366. * @param target the target Vector3 to look at
  80367. * @param settings optional settings:
  80368. * * maxYaw: the maximum angle the bone will yaw to
  80369. * * minYaw: the minimum angle the bone will yaw to
  80370. * * maxPitch: the maximum angle the bone will pitch to
  80371. * * minPitch: the minimum angle the bone will yaw to
  80372. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80373. * * upAxis: the up axis of the coordinate system
  80374. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80375. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80376. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80377. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80378. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80379. * * adjustRoll: used to make an adjustment to the roll of the bone
  80380. **/
  80381. function BoneLookController(mesh, bone, target, options) {
  80382. /**
  80383. * The up axis of the coordinate system that is used when the bone is rotated
  80384. */
  80385. this.upAxis = BABYLON.Vector3.Up();
  80386. /**
  80387. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80388. */
  80389. this.upAxisSpace = BABYLON.Space.LOCAL;
  80390. /**
  80391. * Used to make an adjustment to the yaw of the bone
  80392. */
  80393. this.adjustYaw = 0;
  80394. /**
  80395. * Used to make an adjustment to the pitch of the bone
  80396. */
  80397. this.adjustPitch = 0;
  80398. /**
  80399. * Used to make an adjustment to the roll of the bone
  80400. */
  80401. this.adjustRoll = 0;
  80402. /**
  80403. * 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)
  80404. */
  80405. this.slerpAmount = 1;
  80406. this._boneQuat = BABYLON.Quaternion.Identity();
  80407. this._slerping = false;
  80408. this._firstFrameSkipped = false;
  80409. this._fowardAxis = BABYLON.Vector3.Forward();
  80410. this.mesh = mesh;
  80411. this.bone = bone;
  80412. this.target = target;
  80413. if (options) {
  80414. if (options.adjustYaw) {
  80415. this.adjustYaw = options.adjustYaw;
  80416. }
  80417. if (options.adjustPitch) {
  80418. this.adjustPitch = options.adjustPitch;
  80419. }
  80420. if (options.adjustRoll) {
  80421. this.adjustRoll = options.adjustRoll;
  80422. }
  80423. if (options.maxYaw != null) {
  80424. this.maxYaw = options.maxYaw;
  80425. }
  80426. else {
  80427. this.maxYaw = Math.PI;
  80428. }
  80429. if (options.minYaw != null) {
  80430. this.minYaw = options.minYaw;
  80431. }
  80432. else {
  80433. this.minYaw = -Math.PI;
  80434. }
  80435. if (options.maxPitch != null) {
  80436. this.maxPitch = options.maxPitch;
  80437. }
  80438. else {
  80439. this.maxPitch = Math.PI;
  80440. }
  80441. if (options.minPitch != null) {
  80442. this.minPitch = options.minPitch;
  80443. }
  80444. else {
  80445. this.minPitch = -Math.PI;
  80446. }
  80447. if (options.slerpAmount != null) {
  80448. this.slerpAmount = options.slerpAmount;
  80449. }
  80450. if (options.upAxis != null) {
  80451. this.upAxis = options.upAxis;
  80452. }
  80453. if (options.upAxisSpace != null) {
  80454. this.upAxisSpace = options.upAxisSpace;
  80455. }
  80456. if (options.yawAxis != null || options.pitchAxis != null) {
  80457. var newYawAxis = BABYLON.Axis.Y;
  80458. var newPitchAxis = BABYLON.Axis.X;
  80459. if (options.yawAxis != null) {
  80460. newYawAxis = options.yawAxis.clone();
  80461. newYawAxis.normalize();
  80462. }
  80463. if (options.pitchAxis != null) {
  80464. newPitchAxis = options.pitchAxis.clone();
  80465. newPitchAxis.normalize();
  80466. }
  80467. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80468. this._transformYawPitch = BABYLON.Matrix.Identity();
  80469. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80470. this._transformYawPitchInv = this._transformYawPitch.clone();
  80471. this._transformYawPitch.invert();
  80472. }
  80473. }
  80474. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80475. this.upAxisSpace = BABYLON.Space.LOCAL;
  80476. }
  80477. }
  80478. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80479. /**
  80480. * Gets or sets the minimum yaw angle that the bone can look to
  80481. */
  80482. get: function () {
  80483. return this._minYaw;
  80484. },
  80485. set: function (value) {
  80486. this._minYaw = value;
  80487. this._minYawSin = Math.sin(value);
  80488. this._minYawCos = Math.cos(value);
  80489. if (this._maxYaw != null) {
  80490. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80491. this._yawRange = this._maxYaw - this._minYaw;
  80492. }
  80493. },
  80494. enumerable: true,
  80495. configurable: true
  80496. });
  80497. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80498. /**
  80499. * Gets or sets the maximum yaw angle that the bone can look to
  80500. */
  80501. get: function () {
  80502. return this._maxYaw;
  80503. },
  80504. set: function (value) {
  80505. this._maxYaw = value;
  80506. this._maxYawSin = Math.sin(value);
  80507. this._maxYawCos = Math.cos(value);
  80508. if (this._minYaw != null) {
  80509. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80510. this._yawRange = this._maxYaw - this._minYaw;
  80511. }
  80512. },
  80513. enumerable: true,
  80514. configurable: true
  80515. });
  80516. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80517. /**
  80518. * Gets or sets the minimum pitch angle that the bone can look to
  80519. */
  80520. get: function () {
  80521. return this._minPitch;
  80522. },
  80523. set: function (value) {
  80524. this._minPitch = value;
  80525. this._minPitchTan = Math.tan(value);
  80526. },
  80527. enumerable: true,
  80528. configurable: true
  80529. });
  80530. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80531. /**
  80532. * Gets or sets the maximum pitch angle that the bone can look to
  80533. */
  80534. get: function () {
  80535. return this._maxPitch;
  80536. },
  80537. set: function (value) {
  80538. this._maxPitch = value;
  80539. this._maxPitchTan = Math.tan(value);
  80540. },
  80541. enumerable: true,
  80542. configurable: true
  80543. });
  80544. /**
  80545. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80546. */
  80547. BoneLookController.prototype.update = function () {
  80548. //skip the first frame when slerping so that the mesh rotation is correct
  80549. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80550. this._firstFrameSkipped = true;
  80551. return;
  80552. }
  80553. var bone = this.bone;
  80554. var bonePos = BoneLookController._tmpVecs[0];
  80555. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80556. var target = this.target;
  80557. var _tmpMat1 = BoneLookController._tmpMats[0];
  80558. var _tmpMat2 = BoneLookController._tmpMats[1];
  80559. var mesh = this.mesh;
  80560. var parentBone = bone.getParent();
  80561. var upAxis = BoneLookController._tmpVecs[1];
  80562. upAxis.copyFrom(this.upAxis);
  80563. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80564. if (this._transformYawPitch) {
  80565. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80566. }
  80567. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80568. }
  80569. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80570. mesh.getDirectionToRef(upAxis, upAxis);
  80571. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80572. upAxis.normalize();
  80573. }
  80574. }
  80575. var checkYaw = false;
  80576. var checkPitch = false;
  80577. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80578. checkYaw = true;
  80579. }
  80580. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80581. checkPitch = true;
  80582. }
  80583. if (checkYaw || checkPitch) {
  80584. var spaceMat = BoneLookController._tmpMats[2];
  80585. var spaceMatInv = BoneLookController._tmpMats[3];
  80586. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80587. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80588. }
  80589. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80590. spaceMat.copyFrom(mesh.getWorldMatrix());
  80591. }
  80592. else {
  80593. var forwardAxis = BoneLookController._tmpVecs[2];
  80594. forwardAxis.copyFrom(this._fowardAxis);
  80595. if (this._transformYawPitch) {
  80596. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80597. }
  80598. if (parentBone) {
  80599. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80600. }
  80601. else {
  80602. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80603. }
  80604. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80605. rightAxis.normalize();
  80606. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80607. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80608. }
  80609. spaceMat.invertToRef(spaceMatInv);
  80610. var xzlen = null;
  80611. if (checkPitch) {
  80612. var localTarget = BoneLookController._tmpVecs[3];
  80613. target.subtractToRef(bonePos, localTarget);
  80614. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80615. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80616. var pitch = Math.atan2(localTarget.y, xzlen);
  80617. var newPitch = pitch;
  80618. if (pitch > this._maxPitch) {
  80619. localTarget.y = this._maxPitchTan * xzlen;
  80620. newPitch = this._maxPitch;
  80621. }
  80622. else if (pitch < this._minPitch) {
  80623. localTarget.y = this._minPitchTan * xzlen;
  80624. newPitch = this._minPitch;
  80625. }
  80626. if (pitch != newPitch) {
  80627. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80628. localTarget.addInPlace(bonePos);
  80629. target = localTarget;
  80630. }
  80631. }
  80632. if (checkYaw) {
  80633. var localTarget = BoneLookController._tmpVecs[4];
  80634. target.subtractToRef(bonePos, localTarget);
  80635. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80636. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80637. var newYaw = yaw;
  80638. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80639. if (xzlen == null) {
  80640. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80641. }
  80642. if (this._yawRange > Math.PI) {
  80643. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80644. localTarget.z = this._maxYawCos * xzlen;
  80645. localTarget.x = this._maxYawSin * xzlen;
  80646. newYaw = this._maxYaw;
  80647. }
  80648. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80649. localTarget.z = this._minYawCos * xzlen;
  80650. localTarget.x = this._minYawSin * xzlen;
  80651. newYaw = this._minYaw;
  80652. }
  80653. }
  80654. else {
  80655. if (yaw > this._maxYaw) {
  80656. localTarget.z = this._maxYawCos * xzlen;
  80657. localTarget.x = this._maxYawSin * xzlen;
  80658. newYaw = this._maxYaw;
  80659. }
  80660. else if (yaw < this._minYaw) {
  80661. localTarget.z = this._minYawCos * xzlen;
  80662. localTarget.x = this._minYawSin * xzlen;
  80663. newYaw = this._minYaw;
  80664. }
  80665. }
  80666. }
  80667. if (this._slerping && this._yawRange > Math.PI) {
  80668. //are we going to be crossing into the min/max region?
  80669. var boneFwd = BoneLookController._tmpVecs[8];
  80670. boneFwd.copyFrom(BABYLON.Axis.Z);
  80671. if (this._transformYawPitch) {
  80672. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80673. }
  80674. var boneRotMat = BoneLookController._tmpMats[4];
  80675. this._boneQuat.toRotationMatrix(boneRotMat);
  80676. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80677. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80678. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80679. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80680. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80681. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80682. if (angBtwTar > angBtwMidYaw) {
  80683. if (xzlen == null) {
  80684. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80685. }
  80686. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80687. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80688. if (angBtwMin < angBtwMax) {
  80689. newYaw = boneYaw + Math.PI * .75;
  80690. localTarget.z = Math.cos(newYaw) * xzlen;
  80691. localTarget.x = Math.sin(newYaw) * xzlen;
  80692. }
  80693. else {
  80694. newYaw = boneYaw - Math.PI * .75;
  80695. localTarget.z = Math.cos(newYaw) * xzlen;
  80696. localTarget.x = Math.sin(newYaw) * xzlen;
  80697. }
  80698. }
  80699. }
  80700. if (yaw != newYaw) {
  80701. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80702. localTarget.addInPlace(bonePos);
  80703. target = localTarget;
  80704. }
  80705. }
  80706. }
  80707. var zaxis = BoneLookController._tmpVecs[5];
  80708. var xaxis = BoneLookController._tmpVecs[6];
  80709. var yaxis = BoneLookController._tmpVecs[7];
  80710. var _tmpQuat = BoneLookController._tmpQuat;
  80711. target.subtractToRef(bonePos, zaxis);
  80712. zaxis.normalize();
  80713. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  80714. xaxis.normalize();
  80715. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  80716. yaxis.normalize();
  80717. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  80718. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  80719. return;
  80720. }
  80721. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  80722. return;
  80723. }
  80724. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  80725. return;
  80726. }
  80727. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  80728. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  80729. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  80730. }
  80731. if (this.slerpAmount < 1) {
  80732. if (!this._slerping) {
  80733. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  80734. }
  80735. if (this._transformYawPitch) {
  80736. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80737. }
  80738. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  80739. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  80740. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  80741. this._slerping = true;
  80742. }
  80743. else {
  80744. if (this._transformYawPitch) {
  80745. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80746. }
  80747. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  80748. this._slerping = false;
  80749. }
  80750. };
  80751. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  80752. var angDiff = ang2 - ang1;
  80753. angDiff %= Math.PI * 2;
  80754. if (angDiff > Math.PI) {
  80755. angDiff -= Math.PI * 2;
  80756. }
  80757. else if (angDiff < -Math.PI) {
  80758. angDiff += Math.PI * 2;
  80759. }
  80760. return angDiff;
  80761. };
  80762. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80763. ang1 %= (2 * Math.PI);
  80764. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80765. ang2 %= (2 * Math.PI);
  80766. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80767. var ab = 0;
  80768. if (ang1 < ang2) {
  80769. ab = ang2 - ang1;
  80770. }
  80771. else {
  80772. ab = ang1 - ang2;
  80773. }
  80774. if (ab > Math.PI) {
  80775. ab = Math.PI * 2 - ab;
  80776. }
  80777. return ab;
  80778. };
  80779. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80780. ang %= (2 * Math.PI);
  80781. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80782. ang1 %= (2 * Math.PI);
  80783. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80784. ang2 %= (2 * Math.PI);
  80785. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80786. if (ang1 < ang2) {
  80787. if (ang > ang1 && ang < ang2) {
  80788. return true;
  80789. }
  80790. }
  80791. else {
  80792. if (ang > ang2 && ang < ang1) {
  80793. return true;
  80794. }
  80795. }
  80796. return false;
  80797. };
  80798. 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()];
  80799. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80800. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80801. return BoneLookController;
  80802. }());
  80803. BABYLON.BoneLookController = BoneLookController;
  80804. })(BABYLON || (BABYLON = {}));
  80805. //# sourceMappingURL=babylon.boneLookController.js.map
  80806. var BABYLON;
  80807. (function (BABYLON) {
  80808. /**
  80809. * Class used to handle skinning animations
  80810. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80811. */
  80812. var Skeleton = /** @class */ (function () {
  80813. /**
  80814. * Creates a new skeleton
  80815. * @param name defines the skeleton name
  80816. * @param id defines the skeleton Id
  80817. * @param scene defines the hosting scene
  80818. */
  80819. function Skeleton(
  80820. /** defines the skeleton name */
  80821. name,
  80822. /** defines the skeleton Id */
  80823. id, scene) {
  80824. this.name = name;
  80825. this.id = id;
  80826. /**
  80827. * Gets the list of child bones
  80828. */
  80829. this.bones = new Array();
  80830. /**
  80831. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80832. */
  80833. this.needInitialSkinMatrix = false;
  80834. this._isDirty = true;
  80835. this._meshesWithPoseMatrix = new Array();
  80836. this._identity = BABYLON.Matrix.Identity();
  80837. this._ranges = {};
  80838. this._lastAbsoluteTransformsUpdateId = -1;
  80839. /**
  80840. * Specifies if the skeleton should be serialized
  80841. */
  80842. this.doNotSerialize = false;
  80843. this._animationPropertiesOverride = null;
  80844. // Events
  80845. /**
  80846. * An observable triggered before computing the skeleton's matrices
  80847. */
  80848. this.onBeforeComputeObservable = new BABYLON.Observable();
  80849. this.bones = [];
  80850. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80851. scene.skeletons.push(this);
  80852. //make sure it will recalculate the matrix next time prepare is called.
  80853. this._isDirty = true;
  80854. }
  80855. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80856. /**
  80857. * Gets or sets the animation properties override
  80858. */
  80859. get: function () {
  80860. if (!this._animationPropertiesOverride) {
  80861. return this._scene.animationPropertiesOverride;
  80862. }
  80863. return this._animationPropertiesOverride;
  80864. },
  80865. set: function (value) {
  80866. this._animationPropertiesOverride = value;
  80867. },
  80868. enumerable: true,
  80869. configurable: true
  80870. });
  80871. // Members
  80872. /**
  80873. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80874. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80875. * @returns a Float32Array containing matrices data
  80876. */
  80877. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80878. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80879. return mesh._bonesTransformMatrices;
  80880. }
  80881. if (!this._transformMatrices) {
  80882. this.prepare();
  80883. }
  80884. return this._transformMatrices;
  80885. };
  80886. /**
  80887. * Gets the current hosting scene
  80888. * @returns a scene object
  80889. */
  80890. Skeleton.prototype.getScene = function () {
  80891. return this._scene;
  80892. };
  80893. // Methods
  80894. /**
  80895. * Gets a string representing the current skeleton data
  80896. * @param fullDetails defines a boolean indicating if we want a verbose version
  80897. * @returns a string representing the current skeleton data
  80898. */
  80899. Skeleton.prototype.toString = function (fullDetails) {
  80900. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80901. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80902. if (fullDetails) {
  80903. ret += ", Ranges: {";
  80904. var first = true;
  80905. for (var name_1 in this._ranges) {
  80906. if (first) {
  80907. ret += ", ";
  80908. first = false;
  80909. }
  80910. ret += name_1;
  80911. }
  80912. ret += "}";
  80913. }
  80914. return ret;
  80915. };
  80916. /**
  80917. * Get bone's index searching by name
  80918. * @param name defines bone's name to search for
  80919. * @return the indice of the bone. Returns -1 if not found
  80920. */
  80921. Skeleton.prototype.getBoneIndexByName = function (name) {
  80922. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80923. if (this.bones[boneIndex].name === name) {
  80924. return boneIndex;
  80925. }
  80926. }
  80927. return -1;
  80928. };
  80929. /**
  80930. * Creater a new animation range
  80931. * @param name defines the name of the range
  80932. * @param from defines the start key
  80933. * @param to defines the end key
  80934. */
  80935. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80936. // check name not already in use
  80937. if (!this._ranges[name]) {
  80938. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80939. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80940. if (this.bones[i].animations[0]) {
  80941. this.bones[i].animations[0].createRange(name, from, to);
  80942. }
  80943. }
  80944. }
  80945. };
  80946. /**
  80947. * Delete a specific animation range
  80948. * @param name defines the name of the range
  80949. * @param deleteFrames defines if frames must be removed as well
  80950. */
  80951. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80952. if (deleteFrames === void 0) { deleteFrames = true; }
  80953. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80954. if (this.bones[i].animations[0]) {
  80955. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80956. }
  80957. }
  80958. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80959. };
  80960. /**
  80961. * Gets a specific animation range
  80962. * @param name defines the name of the range to look for
  80963. * @returns the requested animation range or null if not found
  80964. */
  80965. Skeleton.prototype.getAnimationRange = function (name) {
  80966. return this._ranges[name];
  80967. };
  80968. /**
  80969. * Gets the list of all animation ranges defined on this skeleton
  80970. * @returns an array
  80971. */
  80972. Skeleton.prototype.getAnimationRanges = function () {
  80973. var animationRanges = [];
  80974. var name;
  80975. var i = 0;
  80976. for (name in this._ranges) {
  80977. animationRanges[i] = this._ranges[name];
  80978. i++;
  80979. }
  80980. return animationRanges;
  80981. };
  80982. /**
  80983. * Copy animation range from a source skeleton.
  80984. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80985. * @param source defines the source skeleton
  80986. * @param name defines the name of the range to copy
  80987. * @param rescaleAsRequired defines if rescaling must be applied if required
  80988. * @returns true if operation was successful
  80989. */
  80990. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80991. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80992. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80993. return false;
  80994. }
  80995. var ret = true;
  80996. var frameOffset = this._getHighestAnimationFrame() + 1;
  80997. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80998. var boneDict = {};
  80999. var sourceBones = source.bones;
  81000. var nBones;
  81001. var i;
  81002. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81003. boneDict[sourceBones[i].name] = sourceBones[i];
  81004. }
  81005. if (this.bones.length !== sourceBones.length) {
  81006. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81007. ret = false;
  81008. }
  81009. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81010. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81011. var boneName = this.bones[i].name;
  81012. var sourceBone = boneDict[boneName];
  81013. if (sourceBone) {
  81014. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81015. }
  81016. else {
  81017. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81018. ret = false;
  81019. }
  81020. }
  81021. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81022. var range = source.getAnimationRange(name);
  81023. if (range) {
  81024. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81025. }
  81026. return ret;
  81027. };
  81028. /**
  81029. * Forces the skeleton to go to rest pose
  81030. */
  81031. Skeleton.prototype.returnToRest = function () {
  81032. for (var index = 0; index < this.bones.length; index++) {
  81033. this.bones[index].returnToRest();
  81034. }
  81035. };
  81036. Skeleton.prototype._getHighestAnimationFrame = function () {
  81037. var ret = 0;
  81038. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81039. if (this.bones[i].animations[0]) {
  81040. var highest = this.bones[i].animations[0].getHighestFrame();
  81041. if (ret < highest) {
  81042. ret = highest;
  81043. }
  81044. }
  81045. }
  81046. return ret;
  81047. };
  81048. /**
  81049. * Begin a specific animation range
  81050. * @param name defines the name of the range to start
  81051. * @param loop defines if looping must be turned on (false by default)
  81052. * @param speedRatio defines the speed ratio to apply (1 by default)
  81053. * @param onAnimationEnd defines a callback which will be called when animation will end
  81054. * @returns a new animatable
  81055. */
  81056. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81057. var range = this.getAnimationRange(name);
  81058. if (!range) {
  81059. return null;
  81060. }
  81061. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81062. };
  81063. /** @hidden */
  81064. Skeleton.prototype._markAsDirty = function () {
  81065. this._isDirty = true;
  81066. };
  81067. /** @hidden */
  81068. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81069. this._meshesWithPoseMatrix.push(mesh);
  81070. };
  81071. /** @hidden */
  81072. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81073. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81074. if (index > -1) {
  81075. this._meshesWithPoseMatrix.splice(index, 1);
  81076. }
  81077. };
  81078. /** @hidden */
  81079. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81080. this.onBeforeComputeObservable.notifyObservers(this);
  81081. for (var index = 0; index < this.bones.length; index++) {
  81082. var bone = this.bones[index];
  81083. var parentBone = bone.getParent();
  81084. if (parentBone) {
  81085. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81086. }
  81087. else {
  81088. if (initialSkinMatrix) {
  81089. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81090. }
  81091. else {
  81092. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81093. }
  81094. }
  81095. if (bone._index !== -1) {
  81096. var mappedIndex = bone._index === null ? index : bone._index;
  81097. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81098. }
  81099. }
  81100. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81101. };
  81102. /**
  81103. * Build all resources required to render a skeleton
  81104. */
  81105. Skeleton.prototype.prepare = function () {
  81106. if (!this._isDirty) {
  81107. return;
  81108. }
  81109. if (this.needInitialSkinMatrix) {
  81110. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81111. var mesh = this._meshesWithPoseMatrix[index];
  81112. var poseMatrix = mesh.getPoseMatrix();
  81113. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81114. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81115. }
  81116. if (this._synchronizedWithMesh !== mesh) {
  81117. this._synchronizedWithMesh = mesh;
  81118. // Prepare bones
  81119. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81120. var bone = this.bones[boneIndex];
  81121. if (!bone.getParent()) {
  81122. var matrix = bone.getBaseMatrix();
  81123. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81124. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81125. }
  81126. }
  81127. }
  81128. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81129. }
  81130. }
  81131. else {
  81132. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81133. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81134. }
  81135. this._computeTransformMatrices(this._transformMatrices, null);
  81136. }
  81137. this._isDirty = false;
  81138. this._scene._activeBones.addCount(this.bones.length, false);
  81139. };
  81140. /**
  81141. * Gets the list of animatables currently running for this skeleton
  81142. * @returns an array of animatables
  81143. */
  81144. Skeleton.prototype.getAnimatables = function () {
  81145. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81146. this._animatables = [];
  81147. for (var index = 0; index < this.bones.length; index++) {
  81148. this._animatables.push(this.bones[index]);
  81149. }
  81150. }
  81151. return this._animatables;
  81152. };
  81153. /**
  81154. * Clone the current skeleton
  81155. * @param name defines the name of the new skeleton
  81156. * @param id defines the id of the enw skeleton
  81157. * @returns the new skeleton
  81158. */
  81159. Skeleton.prototype.clone = function (name, id) {
  81160. var result = new Skeleton(name, id || name, this._scene);
  81161. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81162. for (var index = 0; index < this.bones.length; index++) {
  81163. var source = this.bones[index];
  81164. var parentBone = null;
  81165. var parent_1 = source.getParent();
  81166. if (parent_1) {
  81167. var parentIndex = this.bones.indexOf(parent_1);
  81168. parentBone = result.bones[parentIndex];
  81169. }
  81170. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81171. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81172. }
  81173. if (this._ranges) {
  81174. result._ranges = {};
  81175. for (var rangeName in this._ranges) {
  81176. var range = this._ranges[rangeName];
  81177. if (range) {
  81178. result._ranges[rangeName] = range.clone();
  81179. }
  81180. }
  81181. }
  81182. this._isDirty = true;
  81183. return result;
  81184. };
  81185. /**
  81186. * Enable animation blending for this skeleton
  81187. * @param blendingSpeed defines the blending speed to apply
  81188. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81189. */
  81190. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81191. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81192. this.bones.forEach(function (bone) {
  81193. bone.animations.forEach(function (animation) {
  81194. animation.enableBlending = true;
  81195. animation.blendingSpeed = blendingSpeed;
  81196. });
  81197. });
  81198. };
  81199. /**
  81200. * Releases all resources associated with the current skeleton
  81201. */
  81202. Skeleton.prototype.dispose = function () {
  81203. this._meshesWithPoseMatrix = [];
  81204. // Animations
  81205. this.getScene().stopAnimation(this);
  81206. // Remove from scene
  81207. this.getScene().removeSkeleton(this);
  81208. };
  81209. /**
  81210. * Serialize the skeleton in a JSON object
  81211. * @returns a JSON object
  81212. */
  81213. Skeleton.prototype.serialize = function () {
  81214. var serializationObject = {};
  81215. serializationObject.name = this.name;
  81216. serializationObject.id = this.id;
  81217. if (this.dimensionsAtRest) {
  81218. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81219. }
  81220. serializationObject.bones = [];
  81221. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81222. for (var index = 0; index < this.bones.length; index++) {
  81223. var bone = this.bones[index];
  81224. var parent_2 = bone.getParent();
  81225. var serializedBone = {
  81226. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81227. name: bone.name,
  81228. matrix: bone.getBaseMatrix().toArray(),
  81229. rest: bone.getRestPose().toArray()
  81230. };
  81231. serializationObject.bones.push(serializedBone);
  81232. if (bone.length) {
  81233. serializedBone.length = bone.length;
  81234. }
  81235. if (bone.metadata) {
  81236. serializedBone.metadata = bone.metadata;
  81237. }
  81238. if (bone.animations && bone.animations.length > 0) {
  81239. serializedBone.animation = bone.animations[0].serialize();
  81240. }
  81241. serializationObject.ranges = [];
  81242. for (var name in this._ranges) {
  81243. var source = this._ranges[name];
  81244. if (!source) {
  81245. continue;
  81246. }
  81247. var range = {};
  81248. range.name = name;
  81249. range.from = source.from;
  81250. range.to = source.to;
  81251. serializationObject.ranges.push(range);
  81252. }
  81253. }
  81254. return serializationObject;
  81255. };
  81256. /**
  81257. * Creates a new skeleton from serialized data
  81258. * @param parsedSkeleton defines the serialized data
  81259. * @param scene defines the hosting scene
  81260. * @returns a new skeleton
  81261. */
  81262. Skeleton.Parse = function (parsedSkeleton, scene) {
  81263. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81264. if (parsedSkeleton.dimensionsAtRest) {
  81265. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81266. }
  81267. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81268. var index;
  81269. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81270. var parsedBone = parsedSkeleton.bones[index];
  81271. var parentBone = null;
  81272. if (parsedBone.parentBoneIndex > -1) {
  81273. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81274. }
  81275. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81276. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81277. if (parsedBone.length) {
  81278. bone.length = parsedBone.length;
  81279. }
  81280. if (parsedBone.metadata) {
  81281. bone.metadata = parsedBone.metadata;
  81282. }
  81283. if (parsedBone.animation) {
  81284. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81285. }
  81286. }
  81287. // placed after bones, so createAnimationRange can cascade down
  81288. if (parsedSkeleton.ranges) {
  81289. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81290. var data = parsedSkeleton.ranges[index];
  81291. skeleton.createAnimationRange(data.name, data.from, data.to);
  81292. }
  81293. }
  81294. return skeleton;
  81295. };
  81296. /**
  81297. * Compute all node absolute transforms
  81298. * @param forceUpdate defines if computation must be done even if cache is up to date
  81299. */
  81300. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81301. if (forceUpdate === void 0) { forceUpdate = false; }
  81302. var renderId = this._scene.getRenderId();
  81303. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81304. this.bones[0].computeAbsoluteTransforms();
  81305. this._lastAbsoluteTransformsUpdateId = renderId;
  81306. }
  81307. };
  81308. /**
  81309. * Gets the root pose matrix
  81310. * @returns a matrix
  81311. */
  81312. Skeleton.prototype.getPoseMatrix = function () {
  81313. var poseMatrix = null;
  81314. if (this._meshesWithPoseMatrix.length > 0) {
  81315. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81316. }
  81317. return poseMatrix;
  81318. };
  81319. /**
  81320. * Sorts bones per internal index
  81321. */
  81322. Skeleton.prototype.sortBones = function () {
  81323. var bones = new Array();
  81324. var visited = new Array(this.bones.length);
  81325. for (var index = 0; index < this.bones.length; index++) {
  81326. this._sortBones(index, bones, visited);
  81327. }
  81328. this.bones = bones;
  81329. };
  81330. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81331. if (visited[index]) {
  81332. return;
  81333. }
  81334. visited[index] = true;
  81335. var bone = this.bones[index];
  81336. if (bone._index === undefined) {
  81337. bone._index = index;
  81338. }
  81339. var parentBone = bone.getParent();
  81340. if (parentBone) {
  81341. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81342. }
  81343. bones.push(bone);
  81344. };
  81345. return Skeleton;
  81346. }());
  81347. BABYLON.Skeleton = Skeleton;
  81348. })(BABYLON || (BABYLON = {}));
  81349. //# sourceMappingURL=babylon.skeleton.js.map
  81350. var BABYLON;
  81351. (function (BABYLON) {
  81352. var SphericalPolynomial = /** @class */ (function () {
  81353. function SphericalPolynomial() {
  81354. this.x = BABYLON.Vector3.Zero();
  81355. this.y = BABYLON.Vector3.Zero();
  81356. this.z = BABYLON.Vector3.Zero();
  81357. this.xx = BABYLON.Vector3.Zero();
  81358. this.yy = BABYLON.Vector3.Zero();
  81359. this.zz = BABYLON.Vector3.Zero();
  81360. this.xy = BABYLON.Vector3.Zero();
  81361. this.yz = BABYLON.Vector3.Zero();
  81362. this.zx = BABYLON.Vector3.Zero();
  81363. }
  81364. SphericalPolynomial.prototype.addAmbient = function (color) {
  81365. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81366. this.xx = this.xx.add(colorVector);
  81367. this.yy = this.yy.add(colorVector);
  81368. this.zz = this.zz.add(colorVector);
  81369. };
  81370. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81371. var result = new SphericalPolynomial();
  81372. result.x = harmonics.L11.scale(1.02333);
  81373. result.y = harmonics.L1_1.scale(1.02333);
  81374. result.z = harmonics.L10.scale(1.02333);
  81375. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81376. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81377. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81378. result.yz = harmonics.L2_1.scale(0.858086);
  81379. result.zx = harmonics.L21.scale(0.858086);
  81380. result.xy = harmonics.L2_2.scale(0.858086);
  81381. result.scale(1.0 / Math.PI);
  81382. return result;
  81383. };
  81384. SphericalPolynomial.prototype.scale = function (scale) {
  81385. this.x = this.x.scale(scale);
  81386. this.y = this.y.scale(scale);
  81387. this.z = this.z.scale(scale);
  81388. this.xx = this.xx.scale(scale);
  81389. this.yy = this.yy.scale(scale);
  81390. this.zz = this.zz.scale(scale);
  81391. this.yz = this.yz.scale(scale);
  81392. this.zx = this.zx.scale(scale);
  81393. this.xy = this.xy.scale(scale);
  81394. };
  81395. return SphericalPolynomial;
  81396. }());
  81397. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81398. var SphericalHarmonics = /** @class */ (function () {
  81399. function SphericalHarmonics() {
  81400. this.L00 = BABYLON.Vector3.Zero();
  81401. this.L1_1 = BABYLON.Vector3.Zero();
  81402. this.L10 = BABYLON.Vector3.Zero();
  81403. this.L11 = BABYLON.Vector3.Zero();
  81404. this.L2_2 = BABYLON.Vector3.Zero();
  81405. this.L2_1 = BABYLON.Vector3.Zero();
  81406. this.L20 = BABYLON.Vector3.Zero();
  81407. this.L21 = BABYLON.Vector3.Zero();
  81408. this.L22 = BABYLON.Vector3.Zero();
  81409. }
  81410. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81411. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81412. var c = colorVector.scale(deltaSolidAngle);
  81413. this.L00 = this.L00.add(c.scale(0.282095));
  81414. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81415. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81416. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81417. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81418. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81419. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81420. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81421. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81422. };
  81423. SphericalHarmonics.prototype.scale = function (scale) {
  81424. this.L00 = this.L00.scale(scale);
  81425. this.L1_1 = this.L1_1.scale(scale);
  81426. this.L10 = this.L10.scale(scale);
  81427. this.L11 = this.L11.scale(scale);
  81428. this.L2_2 = this.L2_2.scale(scale);
  81429. this.L2_1 = this.L2_1.scale(scale);
  81430. this.L20 = this.L20.scale(scale);
  81431. this.L21 = this.L21.scale(scale);
  81432. this.L22 = this.L22.scale(scale);
  81433. };
  81434. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81435. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81436. //
  81437. // E_lm = A_l * L_lm
  81438. //
  81439. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81440. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81441. // the scaling factors are given in equation 9.
  81442. // Constant (Band 0)
  81443. this.L00 = this.L00.scale(3.141593);
  81444. // Linear (Band 1)
  81445. this.L1_1 = this.L1_1.scale(2.094395);
  81446. this.L10 = this.L10.scale(2.094395);
  81447. this.L11 = this.L11.scale(2.094395);
  81448. // Quadratic (Band 2)
  81449. this.L2_2 = this.L2_2.scale(0.785398);
  81450. this.L2_1 = this.L2_1.scale(0.785398);
  81451. this.L20 = this.L20.scale(0.785398);
  81452. this.L21 = this.L21.scale(0.785398);
  81453. this.L22 = this.L22.scale(0.785398);
  81454. };
  81455. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81456. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81457. // L = (1/pi) * E * rho
  81458. //
  81459. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81460. this.scale(1.0 / Math.PI);
  81461. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81462. // (The pixel shader must apply albedo after texture fetches, etc).
  81463. };
  81464. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81465. var result = new SphericalHarmonics();
  81466. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81467. result.L1_1 = polynomial.y.scale(0.977204);
  81468. result.L10 = polynomial.z.scale(0.977204);
  81469. result.L11 = polynomial.x.scale(0.977204);
  81470. result.L2_2 = polynomial.xy.scale(1.16538);
  81471. result.L2_1 = polynomial.yz.scale(1.16538);
  81472. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81473. result.L21 = polynomial.zx.scale(1.16538);
  81474. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81475. result.scale(Math.PI);
  81476. return result;
  81477. };
  81478. return SphericalHarmonics;
  81479. }());
  81480. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81481. })(BABYLON || (BABYLON = {}));
  81482. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81483. var BABYLON;
  81484. (function (BABYLON) {
  81485. var FileFaceOrientation = /** @class */ (function () {
  81486. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81487. this.name = name;
  81488. this.worldAxisForNormal = worldAxisForNormal;
  81489. this.worldAxisForFileX = worldAxisForFileX;
  81490. this.worldAxisForFileY = worldAxisForFileY;
  81491. }
  81492. return FileFaceOrientation;
  81493. }());
  81494. ;
  81495. /**
  81496. * Helper class dealing with the extraction of spherical polynomial dataArray
  81497. * from a cube map.
  81498. */
  81499. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81500. function CubeMapToSphericalPolynomialTools() {
  81501. }
  81502. /**
  81503. * Converts a texture to the according Spherical Polynomial data.
  81504. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81505. *
  81506. * @param texture The texture to extract the information from.
  81507. * @return The Spherical Polynomial data.
  81508. */
  81509. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81510. if (!texture.isCube) {
  81511. // Only supports cube Textures currently.
  81512. return null;
  81513. }
  81514. var size = texture.getSize().width;
  81515. var right = texture.readPixels(0);
  81516. var left = texture.readPixels(1);
  81517. var up;
  81518. var down;
  81519. if (texture.isRenderTarget) {
  81520. up = texture.readPixels(3);
  81521. down = texture.readPixels(2);
  81522. }
  81523. else {
  81524. up = texture.readPixels(2);
  81525. down = texture.readPixels(3);
  81526. }
  81527. var front = texture.readPixels(4);
  81528. var back = texture.readPixels(5);
  81529. var gammaSpace = texture.gammaSpace;
  81530. // Always read as RGBA.
  81531. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81532. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81533. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81534. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81535. }
  81536. var cubeInfo = {
  81537. size: size,
  81538. right: right,
  81539. left: left,
  81540. up: up,
  81541. down: down,
  81542. front: front,
  81543. back: back,
  81544. format: format,
  81545. type: type,
  81546. gammaSpace: gammaSpace,
  81547. };
  81548. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81549. };
  81550. /**
  81551. * Converts a cubemap to the according Spherical Polynomial data.
  81552. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81553. *
  81554. * @param cubeInfo The Cube map to extract the information from.
  81555. * @return The Spherical Polynomial data.
  81556. */
  81557. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81558. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81559. var totalSolidAngle = 0.0;
  81560. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81561. var du = 2.0 / cubeInfo.size;
  81562. var dv = du;
  81563. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81564. var minUV = du * 0.5 - 1.0;
  81565. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81566. var fileFace = this.FileFaces[faceIndex];
  81567. var dataArray = cubeInfo[fileFace.name];
  81568. var v = minUV;
  81569. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81570. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81571. // Because SP is still linear, so summation is fine in that basis.
  81572. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81573. for (var y = 0; y < cubeInfo.size; y++) {
  81574. var u = minUV;
  81575. for (var x = 0; x < cubeInfo.size; x++) {
  81576. // World direction (not normalised)
  81577. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81578. worldDirection.normalize();
  81579. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81580. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81581. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81582. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81583. // Handle Integer types.
  81584. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81585. r /= 255;
  81586. g /= 255;
  81587. b /= 255;
  81588. }
  81589. // Handle Gamma space textures.
  81590. if (cubeInfo.gammaSpace) {
  81591. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81592. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81593. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81594. }
  81595. var color = new BABYLON.Color3(r, g, b);
  81596. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81597. totalSolidAngle += deltaSolidAngle;
  81598. u += du;
  81599. }
  81600. v += dv;
  81601. }
  81602. }
  81603. // Solid angle for entire sphere is 4*pi
  81604. var sphereSolidAngle = 4.0 * Math.PI;
  81605. // Adjust the solid angle to allow for how many faces we processed.
  81606. var facesProcessed = 6.0;
  81607. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81608. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81609. // This is needed because the numerical integration over the cube uses a
  81610. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81611. // and also to compensate for accumulative error due to float precision in the summation.
  81612. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81613. sphericalHarmonics.scale(correctionFactor);
  81614. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81615. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81616. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81617. };
  81618. CubeMapToSphericalPolynomialTools.FileFaces = [
  81619. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81620. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81621. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81622. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81623. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81624. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81625. ];
  81626. return CubeMapToSphericalPolynomialTools;
  81627. }());
  81628. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81629. })(BABYLON || (BABYLON = {}));
  81630. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81631. var BABYLON;
  81632. (function (BABYLON) {
  81633. /**
  81634. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81635. */
  81636. var PanoramaToCubeMapTools = /** @class */ (function () {
  81637. function PanoramaToCubeMapTools() {
  81638. }
  81639. /**
  81640. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81641. *
  81642. * @param float32Array The source data.
  81643. * @param inputWidth The width of the input panorama.
  81644. * @param inputhHeight The height of the input panorama.
  81645. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81646. * @return The cubemap data
  81647. */
  81648. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81649. if (!float32Array) {
  81650. throw "ConvertPanoramaToCubemap: input cannot be null";
  81651. }
  81652. if (float32Array.length != inputWidth * inputHeight * 3) {
  81653. throw "ConvertPanoramaToCubemap: input size is wrong";
  81654. }
  81655. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81656. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81657. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81658. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81659. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81660. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81661. return {
  81662. front: textureFront,
  81663. back: textureBack,
  81664. left: textureLeft,
  81665. right: textureRight,
  81666. up: textureUp,
  81667. down: textureDown,
  81668. size: size,
  81669. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81670. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81671. gammaSpace: false,
  81672. };
  81673. };
  81674. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81675. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81676. var textureArray = new Float32Array(buffer);
  81677. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  81678. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  81679. var dy = 1 / texSize;
  81680. var fy = 0;
  81681. for (var y = 0; y < texSize; y++) {
  81682. var xv1 = faceData[0];
  81683. var xv2 = faceData[2];
  81684. for (var x = 0; x < texSize; x++) {
  81685. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  81686. v.normalize();
  81687. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  81688. // 3 channels per pixels
  81689. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  81690. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  81691. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  81692. xv1 = xv1.add(rotDX1);
  81693. xv2 = xv2.add(rotDX2);
  81694. }
  81695. fy += dy;
  81696. }
  81697. return textureArray;
  81698. };
  81699. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  81700. var theta = Math.atan2(vDir.z, vDir.x);
  81701. var phi = Math.acos(vDir.y);
  81702. while (theta < -Math.PI)
  81703. theta += 2 * Math.PI;
  81704. while (theta > Math.PI)
  81705. theta -= 2 * Math.PI;
  81706. var dx = theta / Math.PI;
  81707. var dy = phi / Math.PI;
  81708. // recenter.
  81709. dx = dx * 0.5 + 0.5;
  81710. var px = Math.round(dx * inputWidth);
  81711. if (px < 0)
  81712. px = 0;
  81713. else if (px >= inputWidth)
  81714. px = inputWidth - 1;
  81715. var py = Math.round(dy * inputHeight);
  81716. if (py < 0)
  81717. py = 0;
  81718. else if (py >= inputHeight)
  81719. py = inputHeight - 1;
  81720. var inputY = (inputHeight - py - 1);
  81721. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  81722. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  81723. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  81724. return {
  81725. r: r,
  81726. g: g,
  81727. b: b
  81728. };
  81729. };
  81730. PanoramaToCubeMapTools.FACE_FRONT = [
  81731. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81732. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81733. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81734. new BABYLON.Vector3(1.0, 1.0, -1.0)
  81735. ];
  81736. PanoramaToCubeMapTools.FACE_BACK = [
  81737. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81738. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81739. new BABYLON.Vector3(1.0, 1.0, 1.0),
  81740. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  81741. ];
  81742. PanoramaToCubeMapTools.FACE_RIGHT = [
  81743. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81744. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81745. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81746. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81747. ];
  81748. PanoramaToCubeMapTools.FACE_LEFT = [
  81749. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81750. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81751. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81752. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  81753. ];
  81754. PanoramaToCubeMapTools.FACE_DOWN = [
  81755. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81756. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81757. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81758. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81759. ];
  81760. PanoramaToCubeMapTools.FACE_UP = [
  81761. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81762. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81763. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81764. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81765. ];
  81766. return PanoramaToCubeMapTools;
  81767. }());
  81768. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81769. })(BABYLON || (BABYLON = {}));
  81770. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81771. var BABYLON;
  81772. (function (BABYLON) {
  81773. ;
  81774. /**
  81775. * This groups tools to convert HDR texture to native colors array.
  81776. */
  81777. var HDRTools = /** @class */ (function () {
  81778. function HDRTools() {
  81779. }
  81780. HDRTools.Ldexp = function (mantissa, exponent) {
  81781. if (exponent > 1023) {
  81782. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81783. }
  81784. if (exponent < -1074) {
  81785. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81786. }
  81787. return mantissa * Math.pow(2, exponent);
  81788. };
  81789. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81790. if (exponent > 0) { /*nonzero pixel*/
  81791. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81792. float32array[index + 0] = red * exponent;
  81793. float32array[index + 1] = green * exponent;
  81794. float32array[index + 2] = blue * exponent;
  81795. }
  81796. else {
  81797. float32array[index + 0] = 0;
  81798. float32array[index + 1] = 0;
  81799. float32array[index + 2] = 0;
  81800. }
  81801. };
  81802. HDRTools.readStringLine = function (uint8array, startIndex) {
  81803. var line = "";
  81804. var character = "";
  81805. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81806. character = String.fromCharCode(uint8array[i]);
  81807. if (character == "\n") {
  81808. break;
  81809. }
  81810. line += character;
  81811. }
  81812. return line;
  81813. };
  81814. /**
  81815. * Reads header information from an RGBE texture stored in a native array.
  81816. * More information on this format are available here:
  81817. * https://en.wikipedia.org/wiki/RGBE_image_format
  81818. *
  81819. * @param uint8array The binary file stored in native array.
  81820. * @return The header information.
  81821. */
  81822. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81823. var height = 0;
  81824. var width = 0;
  81825. var line = this.readStringLine(uint8array, 0);
  81826. if (line[0] != '#' || line[1] != '?') {
  81827. throw "Bad HDR Format.";
  81828. }
  81829. var endOfHeader = false;
  81830. var findFormat = false;
  81831. var lineIndex = 0;
  81832. do {
  81833. lineIndex += (line.length + 1);
  81834. line = this.readStringLine(uint8array, lineIndex);
  81835. if (line == "FORMAT=32-bit_rle_rgbe") {
  81836. findFormat = true;
  81837. }
  81838. else if (line.length == 0) {
  81839. endOfHeader = true;
  81840. }
  81841. } while (!endOfHeader);
  81842. if (!findFormat) {
  81843. throw "HDR Bad header format, unsupported FORMAT";
  81844. }
  81845. lineIndex += (line.length + 1);
  81846. line = this.readStringLine(uint8array, lineIndex);
  81847. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81848. var match = sizeRegexp.exec(line);
  81849. // TODO. Support +Y and -X if needed.
  81850. if (!match || match.length < 3) {
  81851. throw "HDR Bad header format, no size";
  81852. }
  81853. width = parseInt(match[2]);
  81854. height = parseInt(match[1]);
  81855. if (width < 8 || width > 0x7fff) {
  81856. throw "HDR Bad header format, unsupported size";
  81857. }
  81858. lineIndex += (line.length + 1);
  81859. return {
  81860. height: height,
  81861. width: width,
  81862. dataPosition: lineIndex
  81863. };
  81864. };
  81865. /**
  81866. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81867. * This RGBE texture needs to store the information as a panorama.
  81868. *
  81869. * More information on this format are available here:
  81870. * https://en.wikipedia.org/wiki/RGBE_image_format
  81871. *
  81872. * @param buffer The binary file stored in an array buffer.
  81873. * @param size The expected size of the extracted cubemap.
  81874. * @return The Cube Map information.
  81875. */
  81876. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81877. var uint8array = new Uint8Array(buffer);
  81878. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81879. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81880. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81881. return cubeMapData;
  81882. };
  81883. /**
  81884. * Returns the pixels data extracted from an RGBE texture.
  81885. * This pixels will be stored left to right up to down in the R G B order in one array.
  81886. *
  81887. * More information on this format are available here:
  81888. * https://en.wikipedia.org/wiki/RGBE_image_format
  81889. *
  81890. * @param uint8array The binary file stored in an array buffer.
  81891. * @param hdrInfo The header information of the file.
  81892. * @return The pixels data in RGB right to left up to down order.
  81893. */
  81894. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81895. // Keep for multi format supports.
  81896. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81897. };
  81898. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81899. var num_scanlines = hdrInfo.height;
  81900. var scanline_width = hdrInfo.width;
  81901. var a, b, c, d, count;
  81902. var dataIndex = hdrInfo.dataPosition;
  81903. var index = 0, endIndex = 0, i = 0;
  81904. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81905. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81906. // 3 channels of 4 bytes per pixel in float.
  81907. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81908. var resultArray = new Float32Array(resultBuffer);
  81909. // read in each successive scanline
  81910. while (num_scanlines > 0) {
  81911. a = uint8array[dataIndex++];
  81912. b = uint8array[dataIndex++];
  81913. c = uint8array[dataIndex++];
  81914. d = uint8array[dataIndex++];
  81915. if (a != 2 || b != 2 || (c & 0x80)) {
  81916. // this file is not run length encoded
  81917. throw "HDR Bad header format, not RLE";
  81918. }
  81919. if (((c << 8) | d) != scanline_width) {
  81920. throw "HDR Bad header format, wrong scan line width";
  81921. }
  81922. index = 0;
  81923. // read each of the four channels for the scanline into the buffer
  81924. for (i = 0; i < 4; i++) {
  81925. endIndex = (i + 1) * scanline_width;
  81926. while (index < endIndex) {
  81927. a = uint8array[dataIndex++];
  81928. b = uint8array[dataIndex++];
  81929. if (a > 128) {
  81930. // a run of the same value
  81931. count = a - 128;
  81932. if ((count == 0) || (count > endIndex - index)) {
  81933. throw "HDR Bad Format, bad scanline data (run)";
  81934. }
  81935. while (count-- > 0) {
  81936. scanLineArray[index++] = b;
  81937. }
  81938. }
  81939. else {
  81940. // a non-run
  81941. count = a;
  81942. if ((count == 0) || (count > endIndex - index)) {
  81943. throw "HDR Bad Format, bad scanline data (non-run)";
  81944. }
  81945. scanLineArray[index++] = b;
  81946. if (--count > 0) {
  81947. for (var j = 0; j < count; j++) {
  81948. scanLineArray[index++] = uint8array[dataIndex++];
  81949. }
  81950. }
  81951. }
  81952. }
  81953. }
  81954. // now convert data from buffer into floats
  81955. for (i = 0; i < scanline_width; i++) {
  81956. a = scanLineArray[i];
  81957. b = scanLineArray[i + scanline_width];
  81958. c = scanLineArray[i + 2 * scanline_width];
  81959. d = scanLineArray[i + 3 * scanline_width];
  81960. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81961. }
  81962. num_scanlines--;
  81963. }
  81964. return resultArray;
  81965. };
  81966. return HDRTools;
  81967. }());
  81968. BABYLON.HDRTools = HDRTools;
  81969. })(BABYLON || (BABYLON = {}));
  81970. //# sourceMappingURL=babylon.hdr.js.map
  81971. var BABYLON;
  81972. (function (BABYLON) {
  81973. /**
  81974. * Sets of helpers addressing the serialization and deserialization of environment texture
  81975. * stored in a BabylonJS env file.
  81976. * Those files are usually stored as .env files.
  81977. */
  81978. var EnvironmentTextureTools = /** @class */ (function () {
  81979. function EnvironmentTextureTools() {
  81980. }
  81981. /**
  81982. * Gets the environment info from an env file.
  81983. * @param data The array buffer containing the .env bytes.
  81984. * @returns the environment file info (the json header) if successfully parsed.
  81985. */
  81986. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81987. var dataView = new DataView(data);
  81988. var pos = 0;
  81989. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81990. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81991. BABYLON.Tools.Error('Not a babylon environment map');
  81992. return null;
  81993. }
  81994. }
  81995. // Read json manifest - collect characters up to null terminator
  81996. var manifestString = '';
  81997. var charCode = 0x00;
  81998. while ((charCode = dataView.getUint8(pos++))) {
  81999. manifestString += String.fromCharCode(charCode);
  82000. }
  82001. var manifest = JSON.parse(manifestString);
  82002. if (manifest.specular) {
  82003. // Extend the header with the position of the payload.
  82004. manifest.specular.specularDataPosition = pos;
  82005. }
  82006. return manifest;
  82007. };
  82008. /**
  82009. * Creates an environment texture from a loaded cube texture.
  82010. * @param texture defines the cube texture to convert in env file
  82011. * @return a promise containing the environment data if succesfull.
  82012. */
  82013. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82014. var _this = this;
  82015. var internalTexture = texture.getInternalTexture();
  82016. if (!internalTexture) {
  82017. return Promise.reject("The cube texture is invalid.");
  82018. }
  82019. if (!texture._prefiltered) {
  82020. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82021. }
  82022. var engine = internalTexture.getEngine();
  82023. if (engine && engine.premultipliedAlpha) {
  82024. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82025. }
  82026. var canvas = engine.getRenderingCanvas();
  82027. if (!canvas) {
  82028. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82029. }
  82030. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82031. if (!engine.getCaps().textureFloatRender) {
  82032. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82033. if (!engine.getCaps().textureHalfFloatRender) {
  82034. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82035. }
  82036. }
  82037. var cubeWidth = internalTexture.width;
  82038. var hostingScene = new BABYLON.Scene(engine);
  82039. var specularTextures = {};
  82040. var promises = [];
  82041. // Read and collect all mipmaps data from the cube.
  82042. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82043. mipmapsCount = Math.round(mipmapsCount);
  82044. var _loop_1 = function (i) {
  82045. var faceWidth = Math.pow(2, mipmapsCount - i);
  82046. var _loop_2 = function (face) {
  82047. var data = texture.readPixels(face, i);
  82048. // Creates a temp texture with the face data.
  82049. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82050. // And rgbdEncode them.
  82051. var promise = new Promise(function (resolve, reject) {
  82052. 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);
  82053. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82054. rgbdPostProcess.onApply = function (effect) {
  82055. effect._bindTexture("textureSampler", tempTexture);
  82056. };
  82057. // As the process needs to happen on the main canvas, keep track of the current size
  82058. var currentW = engine.getRenderWidth();
  82059. var currentH = engine.getRenderHeight();
  82060. // Set the desired size for the texture
  82061. engine.setSize(faceWidth, faceWidth);
  82062. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82063. // Reading datas from WebGL
  82064. canvas.toBlob(function (blob) {
  82065. var fileReader = new FileReader();
  82066. fileReader.onload = function (event) {
  82067. var arrayBuffer = event.target.result;
  82068. specularTextures[i * 6 + face] = arrayBuffer;
  82069. resolve();
  82070. };
  82071. fileReader.readAsArrayBuffer(blob);
  82072. });
  82073. // Reapply the previous canvas size
  82074. engine.setSize(currentW, currentH);
  82075. });
  82076. });
  82077. promises.push(promise);
  82078. };
  82079. // All faces of the cube.
  82080. for (var face = 0; face < 6; face++) {
  82081. _loop_2(face);
  82082. }
  82083. };
  82084. for (var i = 0; i <= mipmapsCount; i++) {
  82085. _loop_1(i);
  82086. }
  82087. // Once all the textures haves been collected as RGBD stored in PNGs
  82088. return Promise.all(promises).then(function () {
  82089. // We can delete the hosting scene keeping track of all the creation objects
  82090. hostingScene.dispose();
  82091. // Creates the json header for the env texture
  82092. var info = {
  82093. version: 1,
  82094. width: cubeWidth,
  82095. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82096. specular: {
  82097. mipmaps: []
  82098. }
  82099. };
  82100. // Sets the specular image data information
  82101. var position = 0;
  82102. for (var i = 0; i <= mipmapsCount; i++) {
  82103. for (var face = 0; face < 6; face++) {
  82104. var byteLength = specularTextures[i * 6 + face].byteLength;
  82105. info.specular.mipmaps.push({
  82106. length: byteLength,
  82107. position: position
  82108. });
  82109. position += byteLength;
  82110. }
  82111. }
  82112. // Encode the JSON as an array buffer
  82113. var infoString = JSON.stringify(info);
  82114. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82115. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82116. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82117. infoView[i] = infoString.charCodeAt(i);
  82118. }
  82119. // Ends up with a null terminator for easier parsing
  82120. infoView[infoString.length] = 0x00;
  82121. // Computes the final required size and creates the storage
  82122. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82123. var finalBuffer = new ArrayBuffer(totalSize);
  82124. var finalBufferView = new Uint8Array(finalBuffer);
  82125. var dataView = new DataView(finalBuffer);
  82126. // Copy the magic bytes identifying the file in
  82127. var pos = 0;
  82128. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82129. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82130. }
  82131. // Add the json info
  82132. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82133. pos += infoBuffer.byteLength;
  82134. // Finally inserts the texture data
  82135. for (var i = 0; i <= mipmapsCount; i++) {
  82136. for (var face = 0; face < 6; face++) {
  82137. var dataBuffer = specularTextures[i * 6 + face];
  82138. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82139. pos += dataBuffer.byteLength;
  82140. }
  82141. }
  82142. // Voila
  82143. return finalBuffer;
  82144. });
  82145. };
  82146. /**
  82147. * Creates a JSON representation of the spherical data.
  82148. * @param texture defines the texture containing the polynomials
  82149. * @return the JSON representation of the spherical info
  82150. */
  82151. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82152. var polynmials = texture.sphericalPolynomial;
  82153. if (polynmials == null) {
  82154. return null;
  82155. }
  82156. return {
  82157. polynomials: true,
  82158. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82159. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82160. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82161. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82162. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82163. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82164. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82165. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82166. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82167. };
  82168. };
  82169. /**
  82170. * Uploads the texture info contained in the env file to te GPU.
  82171. * @param texture defines the internal texture to upload to
  82172. * @param arrayBuffer defines the buffer cotaining the data to load
  82173. * @param info defines the texture info retrieved through the GetEnvInfo method
  82174. * @returns a promise
  82175. */
  82176. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82177. if (info.version !== 1) {
  82178. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82179. }
  82180. var specularInfo = info.specular;
  82181. if (!specularInfo) {
  82182. // Nothing else parsed so far
  82183. return Promise.resolve();
  82184. }
  82185. // Double checks the enclosed info
  82186. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82187. mipmapsCount = Math.round(mipmapsCount) + 1;
  82188. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82189. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82190. }
  82191. // Gets everything ready.
  82192. var engine = texture.getEngine();
  82193. var expandTexture = false;
  82194. var generateNonLODTextures = false;
  82195. var rgbdPostProcess = null;
  82196. var cubeRtt = null;
  82197. var lodTextures = null;
  82198. var caps = engine.getCaps();
  82199. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82200. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82201. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82202. // Add extra process if texture lod is not supported
  82203. if (!caps.textureLOD) {
  82204. expandTexture = false;
  82205. generateNonLODTextures = true;
  82206. lodTextures = {};
  82207. }
  82208. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82209. else if (engine.webGLVersion < 2) {
  82210. expandTexture = false;
  82211. }
  82212. // If half float available we can uncompress the texture
  82213. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82214. expandTexture = true;
  82215. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82216. }
  82217. // If full float available we can uncompress the texture
  82218. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82219. expandTexture = true;
  82220. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82221. }
  82222. // Expand the texture if possible
  82223. if (expandTexture) {
  82224. // Simply run through the decode PP
  82225. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82226. texture._isRGBD = false;
  82227. texture.invertY = false;
  82228. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82229. generateDepthBuffer: false,
  82230. generateMipMaps: true,
  82231. generateStencilBuffer: false,
  82232. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82233. type: texture.type,
  82234. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82235. });
  82236. }
  82237. else {
  82238. texture._isRGBD = true;
  82239. texture.invertY = true;
  82240. // In case of missing support, applies the same patch than DDS files.
  82241. if (generateNonLODTextures) {
  82242. var mipSlices = 3;
  82243. var scale = texture._lodGenerationScale;
  82244. var offset = texture._lodGenerationOffset;
  82245. for (var i = 0; i < mipSlices; i++) {
  82246. //compute LOD from even spacing in smoothness (matching shader calculation)
  82247. var smoothness = i / (mipSlices - 1);
  82248. var roughness = 1 - smoothness;
  82249. var minLODIndex = offset; // roughness = 0
  82250. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82251. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82252. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82253. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82254. glTextureFromLod.isCube = true;
  82255. glTextureFromLod.invertY = true;
  82256. glTextureFromLod.generateMipMaps = false;
  82257. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82258. // Wrap in a base texture for easy binding.
  82259. var lodTexture = new BABYLON.BaseTexture(null);
  82260. lodTexture.isCube = true;
  82261. lodTexture._texture = glTextureFromLod;
  82262. lodTextures[mipmapIndex] = lodTexture;
  82263. switch (i) {
  82264. case 0:
  82265. texture._lodTextureLow = lodTexture;
  82266. break;
  82267. case 1:
  82268. texture._lodTextureMid = lodTexture;
  82269. break;
  82270. case 2:
  82271. texture._lodTextureHigh = lodTexture;
  82272. break;
  82273. }
  82274. }
  82275. }
  82276. }
  82277. var promises = [];
  82278. var _loop_3 = function (i) {
  82279. var _loop_4 = function (face) {
  82280. // Retrieves the face data
  82281. var imageData = specularInfo.mipmaps[i * 6 + face];
  82282. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82283. // Constructs an image element from bytes
  82284. var blob = new Blob([bytes], { type: 'image/png' });
  82285. var url = URL.createObjectURL(blob);
  82286. var image = new Image();
  82287. image.src = url;
  82288. // Enqueue promise to upload to the texture.
  82289. var promise = new Promise(function (resolve, reject) {
  82290. ;
  82291. image.onload = function () {
  82292. if (expandTexture) {
  82293. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82294. reject(message);
  82295. }, image);
  82296. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82297. // Uncompress the data to a RTT
  82298. rgbdPostProcess.onApply = function (effect) {
  82299. effect._bindTexture("textureSampler", tempTexture_1);
  82300. effect.setFloat2("scale", 1, 1);
  82301. };
  82302. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82303. // Cleanup
  82304. engine.restoreDefaultFramebuffer();
  82305. tempTexture_1.dispose();
  82306. window.URL.revokeObjectURL(url);
  82307. resolve();
  82308. });
  82309. }
  82310. else {
  82311. engine._uploadImageToTexture(texture, face, i, image);
  82312. // Upload the face to the none lod texture support
  82313. if (generateNonLODTextures) {
  82314. var lodTexture = lodTextures[i];
  82315. if (lodTexture) {
  82316. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82317. }
  82318. }
  82319. resolve();
  82320. }
  82321. };
  82322. image.onerror = function (error) {
  82323. reject(error);
  82324. };
  82325. });
  82326. promises.push(promise);
  82327. };
  82328. // All faces
  82329. for (var face = 0; face < 6; face++) {
  82330. _loop_4(face);
  82331. }
  82332. };
  82333. // All mipmaps
  82334. for (var i = 0; i < mipmapsCount; i++) {
  82335. _loop_3(i);
  82336. }
  82337. // Once all done, finishes the cleanup and return
  82338. return Promise.all(promises).then(function () {
  82339. // Relase temp RTT.
  82340. if (cubeRtt) {
  82341. engine._releaseFramebufferObjects(cubeRtt);
  82342. cubeRtt._swapAndDie(texture);
  82343. }
  82344. // Relase temp Post Process.
  82345. if (rgbdPostProcess) {
  82346. rgbdPostProcess.dispose();
  82347. }
  82348. // Flag internal texture as ready in case they are in use.
  82349. if (generateNonLODTextures) {
  82350. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82351. texture._lodTextureHigh._texture.isReady = true;
  82352. }
  82353. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82354. texture._lodTextureMid._texture.isReady = true;
  82355. }
  82356. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82357. texture._lodTextureLow._texture.isReady = true;
  82358. }
  82359. }
  82360. });
  82361. };
  82362. /**
  82363. * Uploads spherical polynomials information to the texture.
  82364. * @param texture defines the texture we are trying to upload the information to
  82365. * @param arrayBuffer defines the array buffer holding the data
  82366. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82367. */
  82368. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82369. if (info.version !== 1) {
  82370. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82371. }
  82372. var irradianceInfo = info.irradiance;
  82373. if (!irradianceInfo) {
  82374. return;
  82375. }
  82376. //harmonics now represent radiance
  82377. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82378. if (irradianceInfo.polynomials) {
  82379. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82380. }
  82381. else {
  82382. // convert From SH to SP.
  82383. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82384. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82385. }
  82386. };
  82387. /**
  82388. * Upload spherical polynomial coefficients to the texture
  82389. * @param polynmials Spherical polynmial coefficients (9)
  82390. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82391. */
  82392. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82393. outPolynomialCoefficents.x.x = polynmials.x[0];
  82394. outPolynomialCoefficents.x.y = polynmials.x[1];
  82395. outPolynomialCoefficents.x.z = polynmials.x[2];
  82396. outPolynomialCoefficents.y.x = polynmials.y[0];
  82397. outPolynomialCoefficents.y.y = polynmials.y[1];
  82398. outPolynomialCoefficents.y.z = polynmials.y[2];
  82399. outPolynomialCoefficents.z.x = polynmials.z[0];
  82400. outPolynomialCoefficents.z.y = polynmials.z[1];
  82401. outPolynomialCoefficents.z.z = polynmials.z[2];
  82402. //xx
  82403. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82404. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82405. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82406. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82407. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82408. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82409. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82410. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82411. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82412. //yz
  82413. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82414. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82415. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82416. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82417. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82418. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82419. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82420. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82421. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82422. };
  82423. /**
  82424. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82425. * L = (1/pi) * E * rho
  82426. *
  82427. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82428. * @param harmonics Spherical harmonic coefficients (9)
  82429. */
  82430. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82431. var scaleFactor = 1 / Math.PI;
  82432. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82433. // (The pixel shader must apply albedo after texture fetches, etc).
  82434. harmonics.l00[0] *= scaleFactor;
  82435. harmonics.l00[1] *= scaleFactor;
  82436. harmonics.l00[2] *= scaleFactor;
  82437. harmonics.l1_1[0] *= scaleFactor;
  82438. harmonics.l1_1[1] *= scaleFactor;
  82439. harmonics.l1_1[2] *= scaleFactor;
  82440. harmonics.l10[0] *= scaleFactor;
  82441. harmonics.l10[1] *= scaleFactor;
  82442. harmonics.l10[2] *= scaleFactor;
  82443. harmonics.l11[0] *= scaleFactor;
  82444. harmonics.l11[1] *= scaleFactor;
  82445. harmonics.l11[2] *= scaleFactor;
  82446. harmonics.l2_2[0] *= scaleFactor;
  82447. harmonics.l2_2[1] *= scaleFactor;
  82448. harmonics.l2_2[2] *= scaleFactor;
  82449. harmonics.l2_1[0] *= scaleFactor;
  82450. harmonics.l2_1[1] *= scaleFactor;
  82451. harmonics.l2_1[2] *= scaleFactor;
  82452. harmonics.l20[0] *= scaleFactor;
  82453. harmonics.l20[1] *= scaleFactor;
  82454. harmonics.l20[2] *= scaleFactor;
  82455. harmonics.l21[0] *= scaleFactor;
  82456. harmonics.l21[1] *= scaleFactor;
  82457. harmonics.l21[2] *= scaleFactor;
  82458. harmonics.l22[0] *= scaleFactor;
  82459. harmonics.l22[1] *= scaleFactor;
  82460. harmonics.l22[2] *= scaleFactor;
  82461. };
  82462. /**
  82463. * Convert spherical harmonics to spherical polynomial coefficients
  82464. * @param harmonics Spherical harmonic coefficients (9)
  82465. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82466. */
  82467. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82468. var rPi = 1 / Math.PI;
  82469. //x
  82470. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82471. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82472. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82473. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82474. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82475. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82476. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82477. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82478. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82479. //xx
  82480. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82481. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82482. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82483. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82484. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82485. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82486. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82487. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82488. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82489. //yz
  82490. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82491. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82492. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82493. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82494. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82495. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82496. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82497. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82498. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82499. };
  82500. /**
  82501. * Magic number identifying the env file.
  82502. */
  82503. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82504. return EnvironmentTextureTools;
  82505. }());
  82506. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82507. })(BABYLON || (BABYLON = {}));
  82508. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82509. var BABYLON;
  82510. (function (BABYLON) {
  82511. /**
  82512. * This represents a texture coming from an HDR input.
  82513. *
  82514. * The only supported format is currently panorama picture stored in RGBE format.
  82515. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82516. */
  82517. var HDRCubeTexture = /** @class */ (function (_super) {
  82518. __extends(HDRCubeTexture, _super);
  82519. /**
  82520. * Instantiates an HDRTexture from the following parameters.
  82521. *
  82522. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82523. * @param scene The scene the texture will be used in
  82524. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82525. * @param noMipmap Forces to not generate the mipmap if true
  82526. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82527. * @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)
  82528. * @param reserved Reserved flag for internal use.
  82529. */
  82530. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82531. if (noMipmap === void 0) { noMipmap = false; }
  82532. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82533. if (gammaSpace === void 0) { gammaSpace = false; }
  82534. if (reserved === void 0) { reserved = false; }
  82535. if (onLoad === void 0) { onLoad = null; }
  82536. if (onError === void 0) { onError = null; }
  82537. var _this = _super.call(this, scene) || this;
  82538. _this._generateHarmonics = true;
  82539. _this._onLoad = null;
  82540. _this._onError = null;
  82541. /**
  82542. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82543. */
  82544. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82545. _this._isBlocking = true;
  82546. _this._rotationY = 0;
  82547. /**
  82548. * Gets or sets the center of the bounding box associated with the cube texture
  82549. * It must define where the camera used to render the texture was set
  82550. */
  82551. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82552. if (!url) {
  82553. return _this;
  82554. }
  82555. _this.name = url;
  82556. _this.url = url;
  82557. _this.hasAlpha = false;
  82558. _this.isCube = true;
  82559. _this._textureMatrix = BABYLON.Matrix.Identity();
  82560. _this._onLoad = onLoad;
  82561. _this._onError = onError;
  82562. _this.gammaSpace = gammaSpace;
  82563. _this._noMipmap = noMipmap;
  82564. _this._size = size;
  82565. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82566. if (!_this._texture) {
  82567. if (!scene.useDelayedTextureLoading) {
  82568. _this.loadTexture();
  82569. }
  82570. else {
  82571. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82572. }
  82573. }
  82574. return _this;
  82575. }
  82576. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82577. /**
  82578. * Gets wether or not the texture is blocking during loading.
  82579. */
  82580. get: function () {
  82581. return this._isBlocking;
  82582. },
  82583. /**
  82584. * Sets wether or not the texture is blocking during loading.
  82585. */
  82586. set: function (value) {
  82587. this._isBlocking = value;
  82588. },
  82589. enumerable: true,
  82590. configurable: true
  82591. });
  82592. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82593. /**
  82594. * Gets texture matrix rotation angle around Y axis radians.
  82595. */
  82596. get: function () {
  82597. return this._rotationY;
  82598. },
  82599. /**
  82600. * Sets texture matrix rotation angle around Y axis in radians.
  82601. */
  82602. set: function (value) {
  82603. this._rotationY = value;
  82604. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82605. },
  82606. enumerable: true,
  82607. configurable: true
  82608. });
  82609. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82610. get: function () {
  82611. return this._boundingBoxSize;
  82612. },
  82613. /**
  82614. * Gets or sets the size of the bounding box associated with the cube texture
  82615. * When defined, the cubemap will switch to local mode
  82616. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82617. * @example https://www.babylonjs-playground.com/#RNASML
  82618. */
  82619. set: function (value) {
  82620. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82621. return;
  82622. }
  82623. this._boundingBoxSize = value;
  82624. var scene = this.getScene();
  82625. if (scene) {
  82626. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82627. }
  82628. },
  82629. enumerable: true,
  82630. configurable: true
  82631. });
  82632. /**
  82633. * Occurs when the file is raw .hdr file.
  82634. */
  82635. HDRCubeTexture.prototype.loadTexture = function () {
  82636. var _this = this;
  82637. var callback = function (buffer) {
  82638. _this.lodGenerationOffset = 0.0;
  82639. _this.lodGenerationScale = 0.8;
  82640. var scene = _this.getScene();
  82641. if (!scene) {
  82642. return null;
  82643. }
  82644. // Extract the raw linear data.
  82645. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82646. // Generate harmonics if needed.
  82647. if (_this._generateHarmonics) {
  82648. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82649. _this.sphericalPolynomial = sphericalPolynomial;
  82650. }
  82651. var results = [];
  82652. var byteArray = null;
  82653. // Push each faces.
  82654. for (var j = 0; j < 6; j++) {
  82655. // Create uintarray fallback.
  82656. if (!scene.getEngine().getCaps().textureFloat) {
  82657. // 3 channels of 1 bytes per pixel in bytes.
  82658. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82659. byteArray = new Uint8Array(byteBuffer);
  82660. }
  82661. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82662. // If special cases.
  82663. if (_this.gammaSpace || byteArray) {
  82664. for (var i = 0; i < _this._size * _this._size; i++) {
  82665. // Put in gamma space if requested.
  82666. if (_this.gammaSpace) {
  82667. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82668. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82669. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82670. }
  82671. // Convert to int texture for fallback.
  82672. if (byteArray) {
  82673. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82674. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82675. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82676. // May use luminance instead if the result is not accurate.
  82677. var max = Math.max(Math.max(r, g), b);
  82678. if (max > 255) {
  82679. var scale = 255 / max;
  82680. r *= scale;
  82681. g *= scale;
  82682. b *= scale;
  82683. }
  82684. byteArray[(i * 3) + 0] = r;
  82685. byteArray[(i * 3) + 1] = g;
  82686. byteArray[(i * 3) + 2] = b;
  82687. }
  82688. }
  82689. }
  82690. if (byteArray) {
  82691. results.push(byteArray);
  82692. }
  82693. else {
  82694. results.push(dataFace);
  82695. }
  82696. }
  82697. return results;
  82698. };
  82699. var scene = this.getScene();
  82700. if (scene) {
  82701. 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);
  82702. }
  82703. };
  82704. HDRCubeTexture.prototype.clone = function () {
  82705. var scene = this.getScene();
  82706. if (!scene) {
  82707. return this;
  82708. }
  82709. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  82710. // Base texture
  82711. newTexture.level = this.level;
  82712. newTexture.wrapU = this.wrapU;
  82713. newTexture.wrapV = this.wrapV;
  82714. newTexture.coordinatesIndex = this.coordinatesIndex;
  82715. newTexture.coordinatesMode = this.coordinatesMode;
  82716. return newTexture;
  82717. };
  82718. // Methods
  82719. HDRCubeTexture.prototype.delayLoad = function () {
  82720. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82721. return;
  82722. }
  82723. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82724. this._texture = this._getFromCache(this.url, this._noMipmap);
  82725. if (!this._texture) {
  82726. this.loadTexture();
  82727. }
  82728. };
  82729. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  82730. return this._textureMatrix;
  82731. };
  82732. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  82733. this._textureMatrix = value;
  82734. };
  82735. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82736. var texture = null;
  82737. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82738. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  82739. texture.name = parsedTexture.name;
  82740. texture.hasAlpha = parsedTexture.hasAlpha;
  82741. texture.level = parsedTexture.level;
  82742. texture.coordinatesMode = parsedTexture.coordinatesMode;
  82743. texture.isBlocking = parsedTexture.isBlocking;
  82744. }
  82745. if (texture) {
  82746. if (parsedTexture.boundingBoxPosition) {
  82747. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  82748. }
  82749. if (parsedTexture.boundingBoxSize) {
  82750. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  82751. }
  82752. if (parsedTexture.rotationY) {
  82753. texture.rotationY = parsedTexture.rotationY;
  82754. }
  82755. }
  82756. return texture;
  82757. };
  82758. HDRCubeTexture.prototype.serialize = function () {
  82759. if (!this.name) {
  82760. return null;
  82761. }
  82762. var serializationObject = {};
  82763. serializationObject.name = this.name;
  82764. serializationObject.hasAlpha = this.hasAlpha;
  82765. serializationObject.isCube = true;
  82766. serializationObject.level = this.level;
  82767. serializationObject.size = this._size;
  82768. serializationObject.coordinatesMode = this.coordinatesMode;
  82769. serializationObject.useInGammaSpace = this.gammaSpace;
  82770. serializationObject.generateHarmonics = this._generateHarmonics;
  82771. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82772. serializationObject.noMipmap = this._noMipmap;
  82773. serializationObject.isBlocking = this._isBlocking;
  82774. serializationObject.rotationY = this._rotationY;
  82775. return serializationObject;
  82776. };
  82777. HDRCubeTexture._facesMapping = [
  82778. "right",
  82779. "left",
  82780. "up",
  82781. "down",
  82782. "front",
  82783. "back"
  82784. ];
  82785. return HDRCubeTexture;
  82786. }(BABYLON.BaseTexture));
  82787. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82788. })(BABYLON || (BABYLON = {}));
  82789. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82790. var BABYLON;
  82791. (function (BABYLON) {
  82792. var IndexedVector2 = /** @class */ (function (_super) {
  82793. __extends(IndexedVector2, _super);
  82794. function IndexedVector2(original, index) {
  82795. var _this = _super.call(this, original.x, original.y) || this;
  82796. _this.index = index;
  82797. return _this;
  82798. }
  82799. return IndexedVector2;
  82800. }(BABYLON.Vector2));
  82801. var PolygonPoints = /** @class */ (function () {
  82802. function PolygonPoints() {
  82803. this.elements = new Array();
  82804. }
  82805. PolygonPoints.prototype.add = function (originalPoints) {
  82806. var _this = this;
  82807. var result = new Array();
  82808. originalPoints.forEach(function (point) {
  82809. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82810. var newPoint = new IndexedVector2(point, _this.elements.length);
  82811. result.push(newPoint);
  82812. _this.elements.push(newPoint);
  82813. }
  82814. });
  82815. return result;
  82816. };
  82817. PolygonPoints.prototype.computeBounds = function () {
  82818. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82819. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82820. this.elements.forEach(function (point) {
  82821. // x
  82822. if (point.x < lmin.x) {
  82823. lmin.x = point.x;
  82824. }
  82825. else if (point.x > lmax.x) {
  82826. lmax.x = point.x;
  82827. }
  82828. // y
  82829. if (point.y < lmin.y) {
  82830. lmin.y = point.y;
  82831. }
  82832. else if (point.y > lmax.y) {
  82833. lmax.y = point.y;
  82834. }
  82835. });
  82836. return {
  82837. min: lmin,
  82838. max: lmax,
  82839. width: lmax.x - lmin.x,
  82840. height: lmax.y - lmin.y
  82841. };
  82842. };
  82843. return PolygonPoints;
  82844. }());
  82845. var Polygon = /** @class */ (function () {
  82846. function Polygon() {
  82847. }
  82848. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82849. return [
  82850. new BABYLON.Vector2(xmin, ymin),
  82851. new BABYLON.Vector2(xmax, ymin),
  82852. new BABYLON.Vector2(xmax, ymax),
  82853. new BABYLON.Vector2(xmin, ymax)
  82854. ];
  82855. };
  82856. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82857. if (cx === void 0) { cx = 0; }
  82858. if (cy === void 0) { cy = 0; }
  82859. if (numberOfSides === void 0) { numberOfSides = 32; }
  82860. var result = new Array();
  82861. var angle = 0;
  82862. var increment = (Math.PI * 2) / numberOfSides;
  82863. for (var i = 0; i < numberOfSides; i++) {
  82864. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82865. angle -= increment;
  82866. }
  82867. return result;
  82868. };
  82869. Polygon.Parse = function (input) {
  82870. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82871. var i, result = [];
  82872. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82873. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82874. }
  82875. return result;
  82876. };
  82877. Polygon.StartingAt = function (x, y) {
  82878. return BABYLON.Path2.StartingAt(x, y);
  82879. };
  82880. return Polygon;
  82881. }());
  82882. BABYLON.Polygon = Polygon;
  82883. var PolygonMeshBuilder = /** @class */ (function () {
  82884. function PolygonMeshBuilder(name, contours, scene) {
  82885. this._points = new PolygonPoints();
  82886. this._outlinepoints = new PolygonPoints();
  82887. this._holes = new Array();
  82888. this._epoints = new Array();
  82889. this._eholes = new Array();
  82890. this._name = name;
  82891. this._scene = scene;
  82892. var points;
  82893. if (contours instanceof BABYLON.Path2) {
  82894. points = contours.getPoints();
  82895. }
  82896. else {
  82897. points = contours;
  82898. }
  82899. this._addToepoint(points);
  82900. this._points.add(points);
  82901. this._outlinepoints.add(points);
  82902. if (typeof earcut === 'undefined') {
  82903. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82904. }
  82905. }
  82906. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82907. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82908. var p = points_1[_i];
  82909. this._epoints.push(p.x, p.y);
  82910. }
  82911. };
  82912. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82913. this._points.add(hole);
  82914. var holepoints = new PolygonPoints();
  82915. holepoints.add(hole);
  82916. this._holes.push(holepoints);
  82917. this._eholes.push(this._epoints.length / 2);
  82918. this._addToepoint(hole);
  82919. return this;
  82920. };
  82921. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82922. var _this = this;
  82923. if (updatable === void 0) { updatable = false; }
  82924. if (depth === void 0) { depth = 0; }
  82925. var result = new BABYLON.Mesh(this._name, this._scene);
  82926. var normals = new Array();
  82927. var positions = new Array();
  82928. var uvs = new Array();
  82929. var bounds = this._points.computeBounds();
  82930. this._points.elements.forEach(function (p) {
  82931. normals.push(0, 1.0, 0);
  82932. positions.push(p.x, 0, p.y);
  82933. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82934. });
  82935. var indices = new Array();
  82936. var res = earcut(this._epoints, this._eholes, 2);
  82937. for (var i = 0; i < res.length; i++) {
  82938. indices.push(res[i]);
  82939. }
  82940. if (depth > 0) {
  82941. var positionscount = (positions.length / 3); //get the current pointcount
  82942. this._points.elements.forEach(function (p) {
  82943. normals.push(0, -1.0, 0);
  82944. positions.push(p.x, -depth, p.y);
  82945. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82946. });
  82947. var totalCount = indices.length;
  82948. for (var i = 0; i < totalCount; i += 3) {
  82949. var i0 = indices[i + 0];
  82950. var i1 = indices[i + 1];
  82951. var i2 = indices[i + 2];
  82952. indices.push(i2 + positionscount);
  82953. indices.push(i1 + positionscount);
  82954. indices.push(i0 + positionscount);
  82955. }
  82956. //Add the sides
  82957. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82958. this._holes.forEach(function (hole) {
  82959. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82960. });
  82961. }
  82962. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82963. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82964. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82965. result.setIndices(indices);
  82966. return result;
  82967. };
  82968. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82969. var StartIndex = positions.length / 3;
  82970. var ulength = 0;
  82971. for (var i = 0; i < points.elements.length; i++) {
  82972. var p = points.elements[i];
  82973. var p1;
  82974. if ((i + 1) > points.elements.length - 1) {
  82975. p1 = points.elements[0];
  82976. }
  82977. else {
  82978. p1 = points.elements[i + 1];
  82979. }
  82980. positions.push(p.x, 0, p.y);
  82981. positions.push(p.x, -depth, p.y);
  82982. positions.push(p1.x, 0, p1.y);
  82983. positions.push(p1.x, -depth, p1.y);
  82984. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82985. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82986. var v3 = v2.subtract(v1);
  82987. var v4 = new BABYLON.Vector3(0, 1, 0);
  82988. var vn = BABYLON.Vector3.Cross(v3, v4);
  82989. vn = vn.normalize();
  82990. uvs.push(ulength / bounds.width, 0);
  82991. uvs.push(ulength / bounds.width, 1);
  82992. ulength += v3.length();
  82993. uvs.push((ulength / bounds.width), 0);
  82994. uvs.push((ulength / bounds.width), 1);
  82995. if (!flip) {
  82996. normals.push(-vn.x, -vn.y, -vn.z);
  82997. normals.push(-vn.x, -vn.y, -vn.z);
  82998. normals.push(-vn.x, -vn.y, -vn.z);
  82999. normals.push(-vn.x, -vn.y, -vn.z);
  83000. indices.push(StartIndex);
  83001. indices.push(StartIndex + 1);
  83002. indices.push(StartIndex + 2);
  83003. indices.push(StartIndex + 1);
  83004. indices.push(StartIndex + 3);
  83005. indices.push(StartIndex + 2);
  83006. }
  83007. else {
  83008. normals.push(vn.x, vn.y, vn.z);
  83009. normals.push(vn.x, vn.y, vn.z);
  83010. normals.push(vn.x, vn.y, vn.z);
  83011. normals.push(vn.x, vn.y, vn.z);
  83012. indices.push(StartIndex);
  83013. indices.push(StartIndex + 2);
  83014. indices.push(StartIndex + 1);
  83015. indices.push(StartIndex + 1);
  83016. indices.push(StartIndex + 2);
  83017. indices.push(StartIndex + 3);
  83018. }
  83019. StartIndex += 4;
  83020. }
  83021. ;
  83022. };
  83023. return PolygonMeshBuilder;
  83024. }());
  83025. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83026. })(BABYLON || (BABYLON = {}));
  83027. //# sourceMappingURL=babylon.polygonMesh.js.map
  83028. var BABYLON;
  83029. (function (BABYLON) {
  83030. // Unique ID when we import meshes from Babylon to CSG
  83031. var currentCSGMeshId = 0;
  83032. // # class Vertex
  83033. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83034. // one to provide additional features like texture coordinates and vertex
  83035. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83036. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83037. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83038. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83039. // is not used anywhere else.
  83040. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83041. var Vertex = /** @class */ (function () {
  83042. function Vertex(pos, normal, uv) {
  83043. this.pos = pos;
  83044. this.normal = normal;
  83045. this.uv = uv;
  83046. }
  83047. Vertex.prototype.clone = function () {
  83048. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83049. };
  83050. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83051. // orientation of a polygon is flipped.
  83052. Vertex.prototype.flip = function () {
  83053. this.normal = this.normal.scale(-1);
  83054. };
  83055. // Create a new vertex between this vertex and `other` by linearly
  83056. // interpolating all properties using a parameter of `t`. Subclasses should
  83057. // override this to interpolate additional properties.
  83058. Vertex.prototype.interpolate = function (other, t) {
  83059. 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));
  83060. };
  83061. return Vertex;
  83062. }());
  83063. // # class Plane
  83064. // Represents a plane in 3D space.
  83065. var Plane = /** @class */ (function () {
  83066. function Plane(normal, w) {
  83067. this.normal = normal;
  83068. this.w = w;
  83069. }
  83070. Plane.FromPoints = function (a, b, c) {
  83071. var v0 = c.subtract(a);
  83072. var v1 = b.subtract(a);
  83073. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83074. return null;
  83075. }
  83076. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83077. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83078. };
  83079. Plane.prototype.clone = function () {
  83080. return new Plane(this.normal.clone(), this.w);
  83081. };
  83082. Plane.prototype.flip = function () {
  83083. this.normal.scaleInPlace(-1);
  83084. this.w = -this.w;
  83085. };
  83086. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83087. // fragments in the appropriate lists. Coplanar polygons go into either
  83088. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83089. // respect to this plane. Polygons in front or in back of this plane go into
  83090. // either `front` or `back`.
  83091. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83092. var COPLANAR = 0;
  83093. var FRONT = 1;
  83094. var BACK = 2;
  83095. var SPANNING = 3;
  83096. // Classify each point as well as the entire polygon into one of the above
  83097. // four classes.
  83098. var polygonType = 0;
  83099. var types = [];
  83100. var i;
  83101. var t;
  83102. for (i = 0; i < polygon.vertices.length; i++) {
  83103. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83104. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83105. polygonType |= type;
  83106. types.push(type);
  83107. }
  83108. // Put the polygon in the correct list, splitting it when necessary.
  83109. switch (polygonType) {
  83110. case COPLANAR:
  83111. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83112. break;
  83113. case FRONT:
  83114. front.push(polygon);
  83115. break;
  83116. case BACK:
  83117. back.push(polygon);
  83118. break;
  83119. case SPANNING:
  83120. var f = [], b = [];
  83121. for (i = 0; i < polygon.vertices.length; i++) {
  83122. var j = (i + 1) % polygon.vertices.length;
  83123. var ti = types[i], tj = types[j];
  83124. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83125. if (ti !== BACK)
  83126. f.push(vi);
  83127. if (ti !== FRONT)
  83128. b.push(ti !== BACK ? vi.clone() : vi);
  83129. if ((ti | tj) === SPANNING) {
  83130. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83131. var v = vi.interpolate(vj, t);
  83132. f.push(v);
  83133. b.push(v.clone());
  83134. }
  83135. }
  83136. var poly;
  83137. if (f.length >= 3) {
  83138. poly = new Polygon(f, polygon.shared);
  83139. if (poly.plane)
  83140. front.push(poly);
  83141. }
  83142. if (b.length >= 3) {
  83143. poly = new Polygon(b, polygon.shared);
  83144. if (poly.plane)
  83145. back.push(poly);
  83146. }
  83147. break;
  83148. }
  83149. };
  83150. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83151. // point is on the plane.
  83152. Plane.EPSILON = 1e-5;
  83153. return Plane;
  83154. }());
  83155. // # class Polygon
  83156. // Represents a convex polygon. The vertices used to initialize a polygon must
  83157. // be coplanar and form a convex loop.
  83158. //
  83159. // Each convex polygon has a `shared` property, which is shared between all
  83160. // polygons that are clones of each other or were split from the same polygon.
  83161. // This can be used to define per-polygon properties (such as surface color).
  83162. var Polygon = /** @class */ (function () {
  83163. function Polygon(vertices, shared) {
  83164. this.vertices = vertices;
  83165. this.shared = shared;
  83166. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83167. }
  83168. Polygon.prototype.clone = function () {
  83169. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83170. return new Polygon(vertices, this.shared);
  83171. };
  83172. Polygon.prototype.flip = function () {
  83173. this.vertices.reverse().map(function (v) { v.flip(); });
  83174. this.plane.flip();
  83175. };
  83176. return Polygon;
  83177. }());
  83178. // # class Node
  83179. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83180. // by picking a polygon to split along. That polygon (and all other coplanar
  83181. // polygons) are added directly to that node and the other polygons are added to
  83182. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83183. // no distinction between internal and leaf nodes.
  83184. var Node = /** @class */ (function () {
  83185. function Node(polygons) {
  83186. this.plane = null;
  83187. this.front = null;
  83188. this.back = null;
  83189. this.polygons = new Array();
  83190. if (polygons) {
  83191. this.build(polygons);
  83192. }
  83193. }
  83194. Node.prototype.clone = function () {
  83195. var node = new Node();
  83196. node.plane = this.plane && this.plane.clone();
  83197. node.front = this.front && this.front.clone();
  83198. node.back = this.back && this.back.clone();
  83199. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83200. return node;
  83201. };
  83202. // Convert solid space to empty space and empty space to solid space.
  83203. Node.prototype.invert = function () {
  83204. for (var i = 0; i < this.polygons.length; i++) {
  83205. this.polygons[i].flip();
  83206. }
  83207. if (this.plane) {
  83208. this.plane.flip();
  83209. }
  83210. if (this.front) {
  83211. this.front.invert();
  83212. }
  83213. if (this.back) {
  83214. this.back.invert();
  83215. }
  83216. var temp = this.front;
  83217. this.front = this.back;
  83218. this.back = temp;
  83219. };
  83220. // Recursively remove all polygons in `polygons` that are inside this BSP
  83221. // tree.
  83222. Node.prototype.clipPolygons = function (polygons) {
  83223. if (!this.plane)
  83224. return polygons.slice();
  83225. var front = new Array(), back = new Array();
  83226. for (var i = 0; i < polygons.length; i++) {
  83227. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83228. }
  83229. if (this.front) {
  83230. front = this.front.clipPolygons(front);
  83231. }
  83232. if (this.back) {
  83233. back = this.back.clipPolygons(back);
  83234. }
  83235. else {
  83236. back = [];
  83237. }
  83238. return front.concat(back);
  83239. };
  83240. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83241. // `bsp`.
  83242. Node.prototype.clipTo = function (bsp) {
  83243. this.polygons = bsp.clipPolygons(this.polygons);
  83244. if (this.front)
  83245. this.front.clipTo(bsp);
  83246. if (this.back)
  83247. this.back.clipTo(bsp);
  83248. };
  83249. // Return a list of all polygons in this BSP tree.
  83250. Node.prototype.allPolygons = function () {
  83251. var polygons = this.polygons.slice();
  83252. if (this.front)
  83253. polygons = polygons.concat(this.front.allPolygons());
  83254. if (this.back)
  83255. polygons = polygons.concat(this.back.allPolygons());
  83256. return polygons;
  83257. };
  83258. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83259. // new polygons are filtered down to the bottom of the tree and become new
  83260. // nodes there. Each set of polygons is partitioned using the first polygon
  83261. // (no heuristic is used to pick a good split).
  83262. Node.prototype.build = function (polygons) {
  83263. if (!polygons.length)
  83264. return;
  83265. if (!this.plane)
  83266. this.plane = polygons[0].plane.clone();
  83267. var front = new Array(), back = new Array();
  83268. for (var i = 0; i < polygons.length; i++) {
  83269. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83270. }
  83271. if (front.length) {
  83272. if (!this.front)
  83273. this.front = new Node();
  83274. this.front.build(front);
  83275. }
  83276. if (back.length) {
  83277. if (!this.back)
  83278. this.back = new Node();
  83279. this.back.build(back);
  83280. }
  83281. };
  83282. return Node;
  83283. }());
  83284. var CSG = /** @class */ (function () {
  83285. function CSG() {
  83286. this.polygons = new Array();
  83287. }
  83288. // Convert BABYLON.Mesh to BABYLON.CSG
  83289. CSG.FromMesh = function (mesh) {
  83290. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83291. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83292. if (mesh instanceof BABYLON.Mesh) {
  83293. mesh.computeWorldMatrix(true);
  83294. matrix = mesh.getWorldMatrix();
  83295. meshPosition = mesh.position.clone();
  83296. meshRotation = mesh.rotation.clone();
  83297. if (mesh.rotationQuaternion) {
  83298. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83299. }
  83300. meshScaling = mesh.scaling.clone();
  83301. }
  83302. else {
  83303. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83304. }
  83305. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83306. var subMeshes = mesh.subMeshes;
  83307. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83308. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83309. vertices = [];
  83310. for (var j = 0; j < 3; j++) {
  83311. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83312. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83313. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83314. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83315. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83316. vertex = new Vertex(position, normal, uv);
  83317. vertices.push(vertex);
  83318. }
  83319. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83320. // To handle the case of degenerated triangle
  83321. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83322. if (polygon.plane)
  83323. polygons.push(polygon);
  83324. }
  83325. }
  83326. var csg = CSG.FromPolygons(polygons);
  83327. csg.matrix = matrix;
  83328. csg.position = meshPosition;
  83329. csg.rotation = meshRotation;
  83330. csg.scaling = meshScaling;
  83331. csg.rotationQuaternion = meshRotationQuaternion;
  83332. currentCSGMeshId++;
  83333. return csg;
  83334. };
  83335. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83336. CSG.FromPolygons = function (polygons) {
  83337. var csg = new CSG();
  83338. csg.polygons = polygons;
  83339. return csg;
  83340. };
  83341. CSG.prototype.clone = function () {
  83342. var csg = new CSG();
  83343. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83344. csg.copyTransformAttributes(this);
  83345. return csg;
  83346. };
  83347. CSG.prototype.union = function (csg) {
  83348. var a = new Node(this.clone().polygons);
  83349. var b = new Node(csg.clone().polygons);
  83350. a.clipTo(b);
  83351. b.clipTo(a);
  83352. b.invert();
  83353. b.clipTo(a);
  83354. b.invert();
  83355. a.build(b.allPolygons());
  83356. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83357. };
  83358. CSG.prototype.unionInPlace = function (csg) {
  83359. var a = new Node(this.polygons);
  83360. var b = new Node(csg.polygons);
  83361. a.clipTo(b);
  83362. b.clipTo(a);
  83363. b.invert();
  83364. b.clipTo(a);
  83365. b.invert();
  83366. a.build(b.allPolygons());
  83367. this.polygons = a.allPolygons();
  83368. };
  83369. CSG.prototype.subtract = function (csg) {
  83370. var a = new Node(this.clone().polygons);
  83371. var b = new Node(csg.clone().polygons);
  83372. a.invert();
  83373. a.clipTo(b);
  83374. b.clipTo(a);
  83375. b.invert();
  83376. b.clipTo(a);
  83377. b.invert();
  83378. a.build(b.allPolygons());
  83379. a.invert();
  83380. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83381. };
  83382. CSG.prototype.subtractInPlace = function (csg) {
  83383. var a = new Node(this.polygons);
  83384. var b = new Node(csg.polygons);
  83385. a.invert();
  83386. a.clipTo(b);
  83387. b.clipTo(a);
  83388. b.invert();
  83389. b.clipTo(a);
  83390. b.invert();
  83391. a.build(b.allPolygons());
  83392. a.invert();
  83393. this.polygons = a.allPolygons();
  83394. };
  83395. CSG.prototype.intersect = function (csg) {
  83396. var a = new Node(this.clone().polygons);
  83397. var b = new Node(csg.clone().polygons);
  83398. a.invert();
  83399. b.clipTo(a);
  83400. b.invert();
  83401. a.clipTo(b);
  83402. b.clipTo(a);
  83403. a.build(b.allPolygons());
  83404. a.invert();
  83405. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83406. };
  83407. CSG.prototype.intersectInPlace = function (csg) {
  83408. var a = new Node(this.polygons);
  83409. var b = new Node(csg.polygons);
  83410. a.invert();
  83411. b.clipTo(a);
  83412. b.invert();
  83413. a.clipTo(b);
  83414. b.clipTo(a);
  83415. a.build(b.allPolygons());
  83416. a.invert();
  83417. this.polygons = a.allPolygons();
  83418. };
  83419. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83420. // not modified.
  83421. CSG.prototype.inverse = function () {
  83422. var csg = this.clone();
  83423. csg.inverseInPlace();
  83424. return csg;
  83425. };
  83426. CSG.prototype.inverseInPlace = function () {
  83427. this.polygons.map(function (p) { p.flip(); });
  83428. };
  83429. // This is used to keep meshes transformations so they can be restored
  83430. // when we build back a Babylon Mesh
  83431. // NB : All CSG operations are performed in world coordinates
  83432. CSG.prototype.copyTransformAttributes = function (csg) {
  83433. this.matrix = csg.matrix;
  83434. this.position = csg.position;
  83435. this.rotation = csg.rotation;
  83436. this.scaling = csg.scaling;
  83437. this.rotationQuaternion = csg.rotationQuaternion;
  83438. return this;
  83439. };
  83440. // Build Raw mesh from CSG
  83441. // Coordinates here are in world space
  83442. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83443. var matrix = this.matrix.clone();
  83444. matrix.invert();
  83445. 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;
  83446. if (keepSubMeshes) {
  83447. // Sort Polygons, since subMeshes are indices range
  83448. polygons.sort(function (a, b) {
  83449. if (a.shared.meshId === b.shared.meshId) {
  83450. return a.shared.subMeshId - b.shared.subMeshId;
  83451. }
  83452. else {
  83453. return a.shared.meshId - b.shared.meshId;
  83454. }
  83455. });
  83456. }
  83457. for (var i = 0, il = polygons.length; i < il; i++) {
  83458. polygon = polygons[i];
  83459. // Building SubMeshes
  83460. if (!subMesh_dict[polygon.shared.meshId]) {
  83461. subMesh_dict[polygon.shared.meshId] = {};
  83462. }
  83463. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83464. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83465. indexStart: +Infinity,
  83466. indexEnd: -Infinity,
  83467. materialIndex: polygon.shared.materialIndex
  83468. };
  83469. }
  83470. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83471. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83472. polygonIndices[0] = 0;
  83473. polygonIndices[1] = j - 1;
  83474. polygonIndices[2] = j;
  83475. for (var k = 0; k < 3; k++) {
  83476. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83477. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83478. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83479. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83480. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83481. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83482. // Check if 2 points can be merged
  83483. if (!(typeof vertex_idx !== 'undefined' &&
  83484. normals[vertex_idx * 3] === localNormal.x &&
  83485. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83486. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83487. uvs[vertex_idx * 2] === uv.x &&
  83488. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83489. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83490. uvs.push(uv.x, uv.y);
  83491. normals.push(normal.x, normal.y, normal.z);
  83492. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83493. }
  83494. indices.push(vertex_idx);
  83495. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83496. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83497. currentIndex++;
  83498. }
  83499. }
  83500. }
  83501. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83502. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83503. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83504. mesh.setIndices(indices, null);
  83505. if (keepSubMeshes) {
  83506. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83507. var materialIndexOffset = 0, materialMaxIndex;
  83508. mesh.subMeshes = new Array();
  83509. for (var m in subMesh_dict) {
  83510. materialMaxIndex = -1;
  83511. for (var sm in subMesh_dict[m]) {
  83512. subMesh_obj = subMesh_dict[m][sm];
  83513. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83514. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83515. }
  83516. materialIndexOffset += ++materialMaxIndex;
  83517. }
  83518. }
  83519. return mesh;
  83520. };
  83521. // Build Mesh from CSG taking material and transforms into account
  83522. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83523. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83524. mesh.material = material;
  83525. mesh.position.copyFrom(this.position);
  83526. mesh.rotation.copyFrom(this.rotation);
  83527. if (this.rotationQuaternion) {
  83528. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83529. }
  83530. mesh.scaling.copyFrom(this.scaling);
  83531. mesh.computeWorldMatrix(true);
  83532. return mesh;
  83533. };
  83534. return CSG;
  83535. }());
  83536. BABYLON.CSG = CSG;
  83537. })(BABYLON || (BABYLON = {}));
  83538. //# sourceMappingURL=babylon.csg.js.map
  83539. var BABYLON;
  83540. (function (BABYLON) {
  83541. var LensFlare = /** @class */ (function () {
  83542. function LensFlare(size, position, color, imgUrl, system) {
  83543. this.size = size;
  83544. this.position = position;
  83545. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83546. this.color = color || new BABYLON.Color3(1, 1, 1);
  83547. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83548. this._system = system;
  83549. system.lensFlares.push(this);
  83550. }
  83551. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83552. return new LensFlare(size, position, color, imgUrl, system);
  83553. };
  83554. LensFlare.prototype.dispose = function () {
  83555. if (this.texture) {
  83556. this.texture.dispose();
  83557. }
  83558. // Remove from scene
  83559. var index = this._system.lensFlares.indexOf(this);
  83560. this._system.lensFlares.splice(index, 1);
  83561. };
  83562. ;
  83563. return LensFlare;
  83564. }());
  83565. BABYLON.LensFlare = LensFlare;
  83566. })(BABYLON || (BABYLON = {}));
  83567. //# sourceMappingURL=babylon.lensFlare.js.map
  83568. var BABYLON;
  83569. (function (BABYLON) {
  83570. var LensFlareSystem = /** @class */ (function () {
  83571. function LensFlareSystem(name, emitter, scene) {
  83572. this.name = name;
  83573. this.lensFlares = new Array();
  83574. this.borderLimit = 300;
  83575. this.viewportBorder = 0;
  83576. this.layerMask = 0x0FFFFFFF;
  83577. this._vertexBuffers = {};
  83578. this._isEnabled = true;
  83579. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83580. this._emitter = emitter;
  83581. this.id = name;
  83582. scene.lensFlareSystems.push(this);
  83583. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83584. var engine = scene.getEngine();
  83585. // VBO
  83586. var vertices = [];
  83587. vertices.push(1, 1);
  83588. vertices.push(-1, 1);
  83589. vertices.push(-1, -1);
  83590. vertices.push(1, -1);
  83591. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83592. // Indices
  83593. var indices = [];
  83594. indices.push(0);
  83595. indices.push(1);
  83596. indices.push(2);
  83597. indices.push(0);
  83598. indices.push(2);
  83599. indices.push(3);
  83600. this._indexBuffer = engine.createIndexBuffer(indices);
  83601. // Effects
  83602. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83603. }
  83604. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83605. get: function () {
  83606. return this._isEnabled;
  83607. },
  83608. set: function (value) {
  83609. this._isEnabled = value;
  83610. },
  83611. enumerable: true,
  83612. configurable: true
  83613. });
  83614. LensFlareSystem.prototype.getScene = function () {
  83615. return this._scene;
  83616. };
  83617. LensFlareSystem.prototype.getEmitter = function () {
  83618. return this._emitter;
  83619. };
  83620. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83621. this._emitter = newEmitter;
  83622. };
  83623. LensFlareSystem.prototype.getEmitterPosition = function () {
  83624. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83625. };
  83626. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83627. var position = this.getEmitterPosition();
  83628. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83629. this._positionX = position.x;
  83630. this._positionY = position.y;
  83631. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83632. if (this.viewportBorder > 0) {
  83633. globalViewport.x -= this.viewportBorder;
  83634. globalViewport.y -= this.viewportBorder;
  83635. globalViewport.width += this.viewportBorder * 2;
  83636. globalViewport.height += this.viewportBorder * 2;
  83637. position.x += this.viewportBorder;
  83638. position.y += this.viewportBorder;
  83639. this._positionX += this.viewportBorder;
  83640. this._positionY += this.viewportBorder;
  83641. }
  83642. if (position.z > 0) {
  83643. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83644. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83645. return true;
  83646. }
  83647. return true;
  83648. }
  83649. return false;
  83650. };
  83651. LensFlareSystem.prototype._isVisible = function () {
  83652. if (!this._isEnabled || !this._scene.activeCamera) {
  83653. return false;
  83654. }
  83655. var emitterPosition = this.getEmitterPosition();
  83656. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  83657. var distance = direction.length();
  83658. direction.normalize();
  83659. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  83660. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  83661. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  83662. };
  83663. LensFlareSystem.prototype.render = function () {
  83664. if (!this._effect.isReady() || !this._scene.activeCamera)
  83665. return false;
  83666. var engine = this._scene.getEngine();
  83667. var viewport = this._scene.activeCamera.viewport;
  83668. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  83669. // Position
  83670. if (!this.computeEffectivePosition(globalViewport)) {
  83671. return false;
  83672. }
  83673. // Visibility
  83674. if (!this._isVisible()) {
  83675. return false;
  83676. }
  83677. // Intensity
  83678. var awayX;
  83679. var awayY;
  83680. if (this._positionX < this.borderLimit + globalViewport.x) {
  83681. awayX = this.borderLimit + globalViewport.x - this._positionX;
  83682. }
  83683. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  83684. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  83685. }
  83686. else {
  83687. awayX = 0;
  83688. }
  83689. if (this._positionY < this.borderLimit + globalViewport.y) {
  83690. awayY = this.borderLimit + globalViewport.y - this._positionY;
  83691. }
  83692. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  83693. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  83694. }
  83695. else {
  83696. awayY = 0;
  83697. }
  83698. var away = (awayX > awayY) ? awayX : awayY;
  83699. away -= this.viewportBorder;
  83700. if (away > this.borderLimit) {
  83701. away = this.borderLimit;
  83702. }
  83703. var intensity = 1.0 - (away / this.borderLimit);
  83704. if (intensity < 0) {
  83705. return false;
  83706. }
  83707. if (intensity > 1.0) {
  83708. intensity = 1.0;
  83709. }
  83710. if (this.viewportBorder > 0) {
  83711. globalViewport.x += this.viewportBorder;
  83712. globalViewport.y += this.viewportBorder;
  83713. globalViewport.width -= this.viewportBorder * 2;
  83714. globalViewport.height -= this.viewportBorder * 2;
  83715. this._positionX -= this.viewportBorder;
  83716. this._positionY -= this.viewportBorder;
  83717. }
  83718. // Position
  83719. var centerX = globalViewport.x + globalViewport.width / 2;
  83720. var centerY = globalViewport.y + globalViewport.height / 2;
  83721. var distX = centerX - this._positionX;
  83722. var distY = centerY - this._positionY;
  83723. // Effects
  83724. engine.enableEffect(this._effect);
  83725. engine.setState(false);
  83726. engine.setDepthBuffer(false);
  83727. // VBOs
  83728. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  83729. // Flares
  83730. for (var index = 0; index < this.lensFlares.length; index++) {
  83731. var flare = this.lensFlares[index];
  83732. engine.setAlphaMode(flare.alphaMode);
  83733. var x = centerX - (distX * flare.position);
  83734. var y = centerY - (distY * flare.position);
  83735. var cw = flare.size;
  83736. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  83737. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  83738. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  83739. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  83740. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  83741. // Texture
  83742. this._effect.setTexture("textureSampler", flare.texture);
  83743. // Color
  83744. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  83745. // Draw order
  83746. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83747. }
  83748. engine.setDepthBuffer(true);
  83749. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83750. return true;
  83751. };
  83752. LensFlareSystem.prototype.dispose = function () {
  83753. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83754. if (vertexBuffer) {
  83755. vertexBuffer.dispose();
  83756. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83757. }
  83758. if (this._indexBuffer) {
  83759. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83760. this._indexBuffer = null;
  83761. }
  83762. while (this.lensFlares.length) {
  83763. this.lensFlares[0].dispose();
  83764. }
  83765. // Remove from scene
  83766. var index = this._scene.lensFlareSystems.indexOf(this);
  83767. this._scene.lensFlareSystems.splice(index, 1);
  83768. };
  83769. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83770. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83771. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83772. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83773. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83774. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83775. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83776. var parsedFlare = parsedLensFlareSystem.flares[index];
  83777. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83778. }
  83779. return lensFlareSystem;
  83780. };
  83781. LensFlareSystem.prototype.serialize = function () {
  83782. var serializationObject = {};
  83783. serializationObject.id = this.id;
  83784. serializationObject.name = this.name;
  83785. serializationObject.emitterId = this.getEmitter().id;
  83786. serializationObject.borderLimit = this.borderLimit;
  83787. serializationObject.flares = [];
  83788. for (var index = 0; index < this.lensFlares.length; index++) {
  83789. var flare = this.lensFlares[index];
  83790. serializationObject.flares.push({
  83791. size: flare.size,
  83792. position: flare.position,
  83793. color: flare.color.asArray(),
  83794. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83795. });
  83796. }
  83797. return serializationObject;
  83798. };
  83799. return LensFlareSystem;
  83800. }());
  83801. BABYLON.LensFlareSystem = LensFlareSystem;
  83802. })(BABYLON || (BABYLON = {}));
  83803. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83804. var BABYLON;
  83805. (function (BABYLON) {
  83806. /**
  83807. * This is a holder class for the physics joint created by the physics plugin.
  83808. * It holds a set of functions to control the underlying joint.
  83809. */
  83810. var PhysicsJoint = /** @class */ (function () {
  83811. function PhysicsJoint(type, jointData) {
  83812. this.type = type;
  83813. this.jointData = jointData;
  83814. jointData.nativeParams = jointData.nativeParams || {};
  83815. }
  83816. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83817. get: function () {
  83818. return this._physicsJoint;
  83819. },
  83820. set: function (newJoint) {
  83821. if (this._physicsJoint) {
  83822. //remove from the wolrd
  83823. }
  83824. this._physicsJoint = newJoint;
  83825. },
  83826. enumerable: true,
  83827. configurable: true
  83828. });
  83829. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83830. set: function (physicsPlugin) {
  83831. this._physicsPlugin = physicsPlugin;
  83832. },
  83833. enumerable: true,
  83834. configurable: true
  83835. });
  83836. /**
  83837. * Execute a function that is physics-plugin specific.
  83838. * @param {Function} func the function that will be executed.
  83839. * It accepts two parameters: the physics world and the physics joint.
  83840. */
  83841. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83842. func(this._physicsPlugin.world, this._physicsJoint);
  83843. };
  83844. //TODO check if the native joints are the same
  83845. //Joint Types
  83846. PhysicsJoint.DistanceJoint = 0;
  83847. PhysicsJoint.HingeJoint = 1;
  83848. PhysicsJoint.BallAndSocketJoint = 2;
  83849. PhysicsJoint.WheelJoint = 3;
  83850. PhysicsJoint.SliderJoint = 4;
  83851. //OIMO
  83852. PhysicsJoint.PrismaticJoint = 5;
  83853. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83854. PhysicsJoint.UniversalJoint = 6;
  83855. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83856. //Cannon
  83857. //Similar to a Ball-Joint. Different in params
  83858. PhysicsJoint.PointToPointJoint = 8;
  83859. //Cannon only at the moment
  83860. PhysicsJoint.SpringJoint = 9;
  83861. PhysicsJoint.LockJoint = 10;
  83862. return PhysicsJoint;
  83863. }());
  83864. BABYLON.PhysicsJoint = PhysicsJoint;
  83865. /**
  83866. * A class representing a physics distance joint.
  83867. */
  83868. var DistanceJoint = /** @class */ (function (_super) {
  83869. __extends(DistanceJoint, _super);
  83870. function DistanceJoint(jointData) {
  83871. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83872. }
  83873. /**
  83874. * Update the predefined distance.
  83875. */
  83876. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83877. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83878. };
  83879. return DistanceJoint;
  83880. }(PhysicsJoint));
  83881. BABYLON.DistanceJoint = DistanceJoint;
  83882. var MotorEnabledJoint = /** @class */ (function (_super) {
  83883. __extends(MotorEnabledJoint, _super);
  83884. function MotorEnabledJoint(type, jointData) {
  83885. return _super.call(this, type, jointData) || this;
  83886. }
  83887. /**
  83888. * Set the motor values.
  83889. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83890. * @param {number} force the force to apply
  83891. * @param {number} maxForce max force for this motor.
  83892. */
  83893. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83894. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83895. };
  83896. /**
  83897. * Set the motor's limits.
  83898. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83899. */
  83900. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83901. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83902. };
  83903. return MotorEnabledJoint;
  83904. }(PhysicsJoint));
  83905. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83906. /**
  83907. * This class represents a single hinge physics joint
  83908. */
  83909. var HingeJoint = /** @class */ (function (_super) {
  83910. __extends(HingeJoint, _super);
  83911. function HingeJoint(jointData) {
  83912. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83913. }
  83914. /**
  83915. * Set the motor values.
  83916. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83917. * @param {number} force the force to apply
  83918. * @param {number} maxForce max force for this motor.
  83919. */
  83920. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83921. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83922. };
  83923. /**
  83924. * Set the motor's limits.
  83925. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83926. */
  83927. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83928. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83929. };
  83930. return HingeJoint;
  83931. }(MotorEnabledJoint));
  83932. BABYLON.HingeJoint = HingeJoint;
  83933. /**
  83934. * This class represents a dual hinge physics joint (same as wheel joint)
  83935. */
  83936. var Hinge2Joint = /** @class */ (function (_super) {
  83937. __extends(Hinge2Joint, _super);
  83938. function Hinge2Joint(jointData) {
  83939. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83940. }
  83941. /**
  83942. * Set the motor values.
  83943. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83944. * @param {number} force the force to apply
  83945. * @param {number} maxForce max force for this motor.
  83946. * @param {motorIndex} the motor's index, 0 or 1.
  83947. */
  83948. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83949. if (motorIndex === void 0) { motorIndex = 0; }
  83950. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83951. };
  83952. /**
  83953. * Set the motor limits.
  83954. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83955. * @param {number} upperLimit the upper limit
  83956. * @param {number} lowerLimit lower limit
  83957. * @param {motorIndex} the motor's index, 0 or 1.
  83958. */
  83959. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83960. if (motorIndex === void 0) { motorIndex = 0; }
  83961. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83962. };
  83963. return Hinge2Joint;
  83964. }(MotorEnabledJoint));
  83965. BABYLON.Hinge2Joint = Hinge2Joint;
  83966. })(BABYLON || (BABYLON = {}));
  83967. //# sourceMappingURL=babylon.physicsJoint.js.map
  83968. var BABYLON;
  83969. (function (BABYLON) {
  83970. var PhysicsImpostor = /** @class */ (function () {
  83971. function PhysicsImpostor(object, type, _options, _scene) {
  83972. if (_options === void 0) { _options = { mass: 0 }; }
  83973. var _this = this;
  83974. this.object = object;
  83975. this.type = type;
  83976. this._options = _options;
  83977. this._scene = _scene;
  83978. this._bodyUpdateRequired = false;
  83979. this._onBeforePhysicsStepCallbacks = new Array();
  83980. this._onAfterPhysicsStepCallbacks = new Array();
  83981. this._onPhysicsCollideCallbacks = [];
  83982. this._deltaPosition = BABYLON.Vector3.Zero();
  83983. this._isDisposed = false;
  83984. //temp variables for parent rotation calculations
  83985. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83986. this._tmpQuat = new BABYLON.Quaternion();
  83987. this._tmpQuat2 = new BABYLON.Quaternion();
  83988. /**
  83989. * this function is executed by the physics engine.
  83990. */
  83991. this.beforeStep = function () {
  83992. if (!_this._physicsEngine) {
  83993. return;
  83994. }
  83995. _this.object.translate(_this._deltaPosition, -1);
  83996. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83997. _this.object.computeWorldMatrix(false);
  83998. if (_this.object.parent && _this.object.rotationQuaternion) {
  83999. _this.getParentsRotation();
  84000. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84001. }
  84002. else {
  84003. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84004. }
  84005. if (!_this._options.disableBidirectionalTransformation) {
  84006. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84007. }
  84008. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84009. func(_this);
  84010. });
  84011. };
  84012. /**
  84013. * this function is executed by the physics engine.
  84014. */
  84015. this.afterStep = function () {
  84016. if (!_this._physicsEngine) {
  84017. return;
  84018. }
  84019. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84020. func(_this);
  84021. });
  84022. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84023. // object has now its world rotation. needs to be converted to local.
  84024. if (_this.object.parent && _this.object.rotationQuaternion) {
  84025. _this.getParentsRotation();
  84026. _this._tmpQuat.conjugateInPlace();
  84027. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84028. }
  84029. // take the position set and make it the absolute position of this object.
  84030. _this.object.setAbsolutePosition(_this.object.position);
  84031. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84032. _this.object.translate(_this._deltaPosition, 1);
  84033. };
  84034. /**
  84035. * Legacy collision detection event support
  84036. */
  84037. this.onCollideEvent = null;
  84038. //event and body object due to cannon's event-based architecture.
  84039. this.onCollide = function (e) {
  84040. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84041. return;
  84042. }
  84043. if (!_this._physicsEngine) {
  84044. return;
  84045. }
  84046. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84047. if (otherImpostor) {
  84048. // Legacy collision detection event support
  84049. if (_this.onCollideEvent) {
  84050. _this.onCollideEvent(_this, otherImpostor);
  84051. }
  84052. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84053. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84054. }).forEach(function (obj) {
  84055. obj.callback(_this, otherImpostor);
  84056. });
  84057. }
  84058. };
  84059. //sanity check!
  84060. if (!this.object) {
  84061. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84062. return;
  84063. }
  84064. //legacy support for old syntax.
  84065. if (!this._scene && object.getScene) {
  84066. this._scene = object.getScene();
  84067. }
  84068. if (!this._scene) {
  84069. return;
  84070. }
  84071. this._physicsEngine = this._scene.getPhysicsEngine();
  84072. if (!this._physicsEngine) {
  84073. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84074. }
  84075. else {
  84076. //set the object's quaternion, if not set
  84077. if (!this.object.rotationQuaternion) {
  84078. if (this.object.rotation) {
  84079. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84080. }
  84081. else {
  84082. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84083. }
  84084. }
  84085. //default options params
  84086. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84087. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84088. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84089. this._joints = [];
  84090. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84091. if (!this.object.parent || this._options.ignoreParent) {
  84092. this._init();
  84093. }
  84094. else if (this.object.parent.physicsImpostor) {
  84095. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84096. }
  84097. }
  84098. }
  84099. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84100. get: function () {
  84101. return this._isDisposed;
  84102. },
  84103. enumerable: true,
  84104. configurable: true
  84105. });
  84106. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84107. get: function () {
  84108. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84109. },
  84110. set: function (value) {
  84111. this.setMass(value);
  84112. },
  84113. enumerable: true,
  84114. configurable: true
  84115. });
  84116. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84117. get: function () {
  84118. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84119. },
  84120. set: function (value) {
  84121. if (!this._physicsEngine) {
  84122. return;
  84123. }
  84124. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84125. },
  84126. enumerable: true,
  84127. configurable: true
  84128. });
  84129. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84130. get: function () {
  84131. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84132. },
  84133. set: function (value) {
  84134. if (!this._physicsEngine) {
  84135. return;
  84136. }
  84137. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84138. },
  84139. enumerable: true,
  84140. configurable: true
  84141. });
  84142. /**
  84143. * This function will completly initialize this impostor.
  84144. * It will create a new body - but only if this mesh has no parent.
  84145. * If it has, this impostor will not be used other than to define the impostor
  84146. * of the child mesh.
  84147. */
  84148. PhysicsImpostor.prototype._init = function () {
  84149. if (!this._physicsEngine) {
  84150. return;
  84151. }
  84152. this._physicsEngine.removeImpostor(this);
  84153. this.physicsBody = null;
  84154. this._parent = this._parent || this._getPhysicsParent();
  84155. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84156. this._physicsEngine.addImpostor(this);
  84157. }
  84158. };
  84159. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84160. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84161. var parentMesh = this.object.parent;
  84162. return parentMesh.physicsImpostor;
  84163. }
  84164. return null;
  84165. };
  84166. /**
  84167. * Should a new body be generated.
  84168. */
  84169. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84170. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84171. };
  84172. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84173. this.forceUpdate();
  84174. };
  84175. /**
  84176. * Force a regeneration of this or the parent's impostor's body.
  84177. * Use under cautious - This will remove all joints already implemented.
  84178. */
  84179. PhysicsImpostor.prototype.forceUpdate = function () {
  84180. this._init();
  84181. if (this.parent && !this._options.ignoreParent) {
  84182. this.parent.forceUpdate();
  84183. }
  84184. };
  84185. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84186. /*public get mesh(): AbstractMesh {
  84187. return this._mesh;
  84188. }*/
  84189. /**
  84190. * Gets the body that holds this impostor. Either its own, or its parent.
  84191. */
  84192. get: function () {
  84193. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84194. },
  84195. /**
  84196. * Set the physics body. Used mainly by the physics engine/plugin
  84197. */
  84198. set: function (physicsBody) {
  84199. if (this._physicsBody && this._physicsEngine) {
  84200. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84201. }
  84202. this._physicsBody = physicsBody;
  84203. this.resetUpdateFlags();
  84204. },
  84205. enumerable: true,
  84206. configurable: true
  84207. });
  84208. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84209. get: function () {
  84210. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84211. },
  84212. set: function (value) {
  84213. this._parent = value;
  84214. },
  84215. enumerable: true,
  84216. configurable: true
  84217. });
  84218. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84219. this._bodyUpdateRequired = false;
  84220. };
  84221. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84222. if (this.object.getBoundingInfo) {
  84223. var q = this.object.rotationQuaternion;
  84224. //reset rotation
  84225. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84226. //calculate the world matrix with no rotation
  84227. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84228. var boundingInfo = this.object.getBoundingInfo();
  84229. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84230. //bring back the rotation
  84231. this.object.rotationQuaternion = q;
  84232. //calculate the world matrix with the new rotation
  84233. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84234. return size;
  84235. }
  84236. else {
  84237. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84238. }
  84239. };
  84240. PhysicsImpostor.prototype.getObjectCenter = function () {
  84241. if (this.object.getBoundingInfo) {
  84242. var boundingInfo = this.object.getBoundingInfo();
  84243. return boundingInfo.boundingBox.centerWorld;
  84244. }
  84245. else {
  84246. return this.object.position;
  84247. }
  84248. };
  84249. /**
  84250. * Get a specific parametes from the options parameter.
  84251. */
  84252. PhysicsImpostor.prototype.getParam = function (paramName) {
  84253. return this._options[paramName];
  84254. };
  84255. /**
  84256. * Sets a specific parameter in the options given to the physics plugin
  84257. */
  84258. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84259. this._options[paramName] = value;
  84260. this._bodyUpdateRequired = true;
  84261. };
  84262. /**
  84263. * Specifically change the body's mass option. Won't recreate the physics body object
  84264. */
  84265. PhysicsImpostor.prototype.setMass = function (mass) {
  84266. if (this.getParam("mass") !== mass) {
  84267. this.setParam("mass", mass);
  84268. }
  84269. if (this._physicsEngine) {
  84270. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84271. }
  84272. };
  84273. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84274. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84275. };
  84276. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84277. if (this._physicsEngine) {
  84278. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84279. }
  84280. };
  84281. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84282. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84283. };
  84284. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84285. if (this._physicsEngine) {
  84286. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84287. }
  84288. };
  84289. /**
  84290. * Execute a function with the physics plugin native code.
  84291. * Provide a function the will have two variables - the world object and the physics body object.
  84292. */
  84293. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84294. if (this._physicsEngine) {
  84295. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84296. }
  84297. };
  84298. /**
  84299. * Register a function that will be executed before the physics world is stepping forward.
  84300. */
  84301. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84302. this._onBeforePhysicsStepCallbacks.push(func);
  84303. };
  84304. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84305. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84306. if (index > -1) {
  84307. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84308. }
  84309. else {
  84310. BABYLON.Tools.Warn("Function to remove was not found");
  84311. }
  84312. };
  84313. /**
  84314. * Register a function that will be executed after the physics step
  84315. */
  84316. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84317. this._onAfterPhysicsStepCallbacks.push(func);
  84318. };
  84319. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84320. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84321. if (index > -1) {
  84322. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84323. }
  84324. else {
  84325. BABYLON.Tools.Warn("Function to remove was not found");
  84326. }
  84327. };
  84328. /**
  84329. * register a function that will be executed when this impostor collides against a different body.
  84330. */
  84331. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84332. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84333. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84334. };
  84335. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84336. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84337. var index = -1;
  84338. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84339. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84340. // chcek the arrays match
  84341. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84342. return collidedAgainstList.indexOf(impostor) > -1;
  84343. });
  84344. if (sameList) {
  84345. index = idx;
  84346. }
  84347. return sameList;
  84348. }
  84349. return false;
  84350. });
  84351. if (found) {
  84352. this._onPhysicsCollideCallbacks.splice(index, 1);
  84353. }
  84354. else {
  84355. BABYLON.Tools.Warn("Function to remove was not found");
  84356. }
  84357. };
  84358. PhysicsImpostor.prototype.getParentsRotation = function () {
  84359. var parent = this.object.parent;
  84360. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84361. while (parent) {
  84362. if (parent.rotationQuaternion) {
  84363. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84364. }
  84365. else {
  84366. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84367. }
  84368. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84369. parent = parent.parent;
  84370. }
  84371. return this._tmpQuat;
  84372. };
  84373. /**
  84374. * Apply a force
  84375. */
  84376. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84377. if (this._physicsEngine) {
  84378. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84379. }
  84380. return this;
  84381. };
  84382. /**
  84383. * Apply an impulse
  84384. */
  84385. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84386. if (this._physicsEngine) {
  84387. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84388. }
  84389. return this;
  84390. };
  84391. /**
  84392. * A help function to create a joint.
  84393. */
  84394. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84395. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84396. this.addJoint(otherImpostor, joint);
  84397. return this;
  84398. };
  84399. /**
  84400. * Add a joint to this impostor with a different impostor.
  84401. */
  84402. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84403. this._joints.push({
  84404. otherImpostor: otherImpostor,
  84405. joint: joint
  84406. });
  84407. if (this._physicsEngine) {
  84408. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84409. }
  84410. return this;
  84411. };
  84412. /**
  84413. * Will keep this body still, in a sleep mode.
  84414. */
  84415. PhysicsImpostor.prototype.sleep = function () {
  84416. if (this._physicsEngine) {
  84417. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84418. }
  84419. return this;
  84420. };
  84421. /**
  84422. * Wake the body up.
  84423. */
  84424. PhysicsImpostor.prototype.wakeUp = function () {
  84425. if (this._physicsEngine) {
  84426. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84427. }
  84428. return this;
  84429. };
  84430. PhysicsImpostor.prototype.clone = function (newObject) {
  84431. if (!newObject)
  84432. return null;
  84433. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84434. };
  84435. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84436. var _this = this;
  84437. //no dispose if no physics engine is available.
  84438. if (!this._physicsEngine) {
  84439. return;
  84440. }
  84441. this._joints.forEach(function (j) {
  84442. if (_this._physicsEngine) {
  84443. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84444. }
  84445. });
  84446. //dispose the physics body
  84447. this._physicsEngine.removeImpostor(this);
  84448. if (this.parent) {
  84449. this.parent.forceUpdate();
  84450. }
  84451. else {
  84452. /*this._object.getChildMeshes().forEach(function(mesh) {
  84453. if (mesh.physicsImpostor) {
  84454. if (disposeChildren) {
  84455. mesh.physicsImpostor.dispose();
  84456. mesh.physicsImpostor = null;
  84457. }
  84458. }
  84459. })*/
  84460. }
  84461. this._isDisposed = true;
  84462. };
  84463. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84464. this._deltaPosition.copyFrom(position);
  84465. };
  84466. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84467. if (!this._deltaRotation) {
  84468. this._deltaRotation = new BABYLON.Quaternion();
  84469. }
  84470. this._deltaRotation.copyFrom(rotation);
  84471. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84472. };
  84473. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84474. if (this._physicsEngine) {
  84475. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84476. }
  84477. return this;
  84478. };
  84479. PhysicsImpostor.prototype.getRadius = function () {
  84480. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84481. };
  84482. /**
  84483. * Sync a bone with this impostor
  84484. * @param bone The bone to sync to the impostor.
  84485. * @param boneMesh The mesh that the bone is influencing.
  84486. * @param jointPivot The pivot of the joint / bone in local space.
  84487. * @param distToJoint Optional distance from the impostor to the joint.
  84488. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84489. */
  84490. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84491. var tempVec = PhysicsImpostor._tmpVecs[0];
  84492. var mesh = this.object;
  84493. if (mesh.rotationQuaternion) {
  84494. if (adjustRotation) {
  84495. var tempQuat = PhysicsImpostor._tmpQuat;
  84496. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84497. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84498. }
  84499. else {
  84500. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84501. }
  84502. }
  84503. tempVec.x = 0;
  84504. tempVec.y = 0;
  84505. tempVec.z = 0;
  84506. if (jointPivot) {
  84507. tempVec.x = jointPivot.x;
  84508. tempVec.y = jointPivot.y;
  84509. tempVec.z = jointPivot.z;
  84510. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84511. if (distToJoint === undefined || distToJoint === null) {
  84512. distToJoint = jointPivot.length();
  84513. }
  84514. tempVec.x *= distToJoint;
  84515. tempVec.y *= distToJoint;
  84516. tempVec.z *= distToJoint;
  84517. }
  84518. if (bone.getParent()) {
  84519. tempVec.addInPlace(mesh.getAbsolutePosition());
  84520. bone.setAbsolutePosition(tempVec, boneMesh);
  84521. }
  84522. else {
  84523. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84524. boneMesh.position.x -= tempVec.x;
  84525. boneMesh.position.y -= tempVec.y;
  84526. boneMesh.position.z -= tempVec.z;
  84527. }
  84528. };
  84529. /**
  84530. * Sync impostor to a bone
  84531. * @param bone The bone that the impostor will be synced to.
  84532. * @param boneMesh The mesh that the bone is influencing.
  84533. * @param jointPivot The pivot of the joint / bone in local space.
  84534. * @param distToJoint Optional distance from the impostor to the joint.
  84535. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84536. * @param boneAxis Optional vector3 axis the bone is aligned with
  84537. */
  84538. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84539. var mesh = this.object;
  84540. if (mesh.rotationQuaternion) {
  84541. if (adjustRotation) {
  84542. var tempQuat = PhysicsImpostor._tmpQuat;
  84543. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84544. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84545. }
  84546. else {
  84547. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84548. }
  84549. }
  84550. var pos = PhysicsImpostor._tmpVecs[0];
  84551. var boneDir = PhysicsImpostor._tmpVecs[1];
  84552. if (!boneAxis) {
  84553. boneAxis = PhysicsImpostor._tmpVecs[2];
  84554. boneAxis.x = 0;
  84555. boneAxis.y = 1;
  84556. boneAxis.z = 0;
  84557. }
  84558. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84559. bone.getAbsolutePositionToRef(boneMesh, pos);
  84560. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84561. distToJoint = jointPivot.length();
  84562. }
  84563. if (distToJoint !== undefined && distToJoint !== null) {
  84564. pos.x += boneDir.x * distToJoint;
  84565. pos.y += boneDir.y * distToJoint;
  84566. pos.z += boneDir.z * distToJoint;
  84567. }
  84568. mesh.setAbsolutePosition(pos);
  84569. };
  84570. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84571. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84572. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84573. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84574. //Impostor types
  84575. PhysicsImpostor.NoImpostor = 0;
  84576. PhysicsImpostor.SphereImpostor = 1;
  84577. PhysicsImpostor.BoxImpostor = 2;
  84578. PhysicsImpostor.PlaneImpostor = 3;
  84579. PhysicsImpostor.MeshImpostor = 4;
  84580. PhysicsImpostor.CylinderImpostor = 7;
  84581. PhysicsImpostor.ParticleImpostor = 8;
  84582. PhysicsImpostor.HeightmapImpostor = 9;
  84583. return PhysicsImpostor;
  84584. }());
  84585. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84586. })(BABYLON || (BABYLON = {}));
  84587. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84588. var BABYLON;
  84589. (function (BABYLON) {
  84590. var PhysicsEngine = /** @class */ (function () {
  84591. function PhysicsEngine(gravity, _physicsPlugin) {
  84592. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84593. this._physicsPlugin = _physicsPlugin;
  84594. //new methods and parameters
  84595. this._impostors = [];
  84596. this._joints = [];
  84597. if (!this._physicsPlugin.isSupported()) {
  84598. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84599. + "Please make sure it is included.");
  84600. }
  84601. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84602. this.setGravity(gravity);
  84603. this.setTimeStep();
  84604. }
  84605. PhysicsEngine.prototype.setGravity = function (gravity) {
  84606. this.gravity = gravity;
  84607. this._physicsPlugin.setGravity(this.gravity);
  84608. };
  84609. /**
  84610. * Set the time step of the physics engine.
  84611. * default is 1/60.
  84612. * To slow it down, enter 1/600 for example.
  84613. * To speed it up, 1/30
  84614. * @param {number} newTimeStep the new timestep to apply to this world.
  84615. */
  84616. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84617. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84618. this._physicsPlugin.setTimeStep(newTimeStep);
  84619. };
  84620. /**
  84621. * Get the time step of the physics engine.
  84622. */
  84623. PhysicsEngine.prototype.getTimeStep = function () {
  84624. return this._physicsPlugin.getTimeStep();
  84625. };
  84626. PhysicsEngine.prototype.dispose = function () {
  84627. this._impostors.forEach(function (impostor) {
  84628. impostor.dispose();
  84629. });
  84630. this._physicsPlugin.dispose();
  84631. };
  84632. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84633. return this._physicsPlugin.name;
  84634. };
  84635. /**
  84636. * Adding a new impostor for the impostor tracking.
  84637. * This will be done by the impostor itself.
  84638. * @param {PhysicsImpostor} impostor the impostor to add
  84639. */
  84640. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84641. impostor.uniqueId = this._impostors.push(impostor);
  84642. //if no parent, generate the body
  84643. if (!impostor.parent) {
  84644. this._physicsPlugin.generatePhysicsBody(impostor);
  84645. }
  84646. };
  84647. /**
  84648. * Remove an impostor from the engine.
  84649. * This impostor and its mesh will not longer be updated by the physics engine.
  84650. * @param {PhysicsImpostor} impostor the impostor to remove
  84651. */
  84652. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  84653. var index = this._impostors.indexOf(impostor);
  84654. if (index > -1) {
  84655. var removed = this._impostors.splice(index, 1);
  84656. //Is it needed?
  84657. if (removed.length) {
  84658. //this will also remove it from the world.
  84659. removed[0].physicsBody = null;
  84660. }
  84661. }
  84662. };
  84663. /**
  84664. * Add a joint to the physics engine
  84665. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  84666. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  84667. * @param {PhysicsJoint} the joint that will connect both impostors.
  84668. */
  84669. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  84670. var impostorJoint = {
  84671. mainImpostor: mainImpostor,
  84672. connectedImpostor: connectedImpostor,
  84673. joint: joint
  84674. };
  84675. joint.physicsPlugin = this._physicsPlugin;
  84676. this._joints.push(impostorJoint);
  84677. this._physicsPlugin.generateJoint(impostorJoint);
  84678. };
  84679. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  84680. var matchingJoints = this._joints.filter(function (impostorJoint) {
  84681. return (impostorJoint.connectedImpostor === connectedImpostor
  84682. && impostorJoint.joint === joint
  84683. && impostorJoint.mainImpostor === mainImpostor);
  84684. });
  84685. if (matchingJoints.length) {
  84686. this._physicsPlugin.removeJoint(matchingJoints[0]);
  84687. //TODO remove it from the list as well
  84688. }
  84689. };
  84690. /**
  84691. * Called by the scene. no need to call it.
  84692. */
  84693. PhysicsEngine.prototype._step = function (delta) {
  84694. var _this = this;
  84695. //check if any mesh has no body / requires an update
  84696. this._impostors.forEach(function (impostor) {
  84697. if (impostor.isBodyInitRequired()) {
  84698. _this._physicsPlugin.generatePhysicsBody(impostor);
  84699. }
  84700. });
  84701. if (delta > 0.1) {
  84702. delta = 0.1;
  84703. }
  84704. else if (delta <= 0) {
  84705. delta = 1.0 / 60.0;
  84706. }
  84707. this._physicsPlugin.executeStep(delta, this._impostors);
  84708. };
  84709. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  84710. return this._physicsPlugin;
  84711. };
  84712. PhysicsEngine.prototype.getImpostors = function () {
  84713. return this._impostors;
  84714. };
  84715. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  84716. for (var i = 0; i < this._impostors.length; ++i) {
  84717. if (this._impostors[i].object === object) {
  84718. return this._impostors[i];
  84719. }
  84720. }
  84721. return null;
  84722. };
  84723. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  84724. for (var i = 0; i < this._impostors.length; ++i) {
  84725. if (this._impostors[i].physicsBody === body) {
  84726. return this._impostors[i];
  84727. }
  84728. }
  84729. return null;
  84730. };
  84731. // Statics
  84732. PhysicsEngine.Epsilon = 0.001;
  84733. return PhysicsEngine;
  84734. }());
  84735. BABYLON.PhysicsEngine = PhysicsEngine;
  84736. })(BABYLON || (BABYLON = {}));
  84737. //# sourceMappingURL=babylon.physicsEngine.js.map
  84738. var BABYLON;
  84739. (function (BABYLON) {
  84740. var PhysicsHelper = /** @class */ (function () {
  84741. function PhysicsHelper(scene) {
  84742. this._scene = scene;
  84743. this._physicsEngine = this._scene.getPhysicsEngine();
  84744. if (!this._physicsEngine) {
  84745. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  84746. }
  84747. }
  84748. /**
  84749. * @param {Vector3} origin the origin of the explosion
  84750. * @param {number} radius the explosion radius
  84751. * @param {number} strength the explosion strength
  84752. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84753. */
  84754. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  84755. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84756. if (!this._physicsEngine) {
  84757. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  84758. return null;
  84759. }
  84760. var impostors = this._physicsEngine.getImpostors();
  84761. if (impostors.length === 0) {
  84762. return null;
  84763. }
  84764. var event = new PhysicsRadialExplosionEvent(this._scene);
  84765. impostors.forEach(function (impostor) {
  84766. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84767. if (!impostorForceAndContactPoint) {
  84768. return;
  84769. }
  84770. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84771. });
  84772. event.dispose(false);
  84773. return event;
  84774. };
  84775. /**
  84776. * @param {Vector3} origin the origin of the explosion
  84777. * @param {number} radius the explosion radius
  84778. * @param {number} strength the explosion strength
  84779. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84780. */
  84781. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84782. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84783. if (!this._physicsEngine) {
  84784. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84785. return null;
  84786. }
  84787. var impostors = this._physicsEngine.getImpostors();
  84788. if (impostors.length === 0) {
  84789. return null;
  84790. }
  84791. var event = new PhysicsRadialExplosionEvent(this._scene);
  84792. impostors.forEach(function (impostor) {
  84793. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84794. if (!impostorForceAndContactPoint) {
  84795. return;
  84796. }
  84797. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84798. });
  84799. event.dispose(false);
  84800. return event;
  84801. };
  84802. /**
  84803. * @param {Vector3} origin the origin of the explosion
  84804. * @param {number} radius the explosion radius
  84805. * @param {number} strength the explosion strength
  84806. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84807. */
  84808. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84809. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84810. if (!this._physicsEngine) {
  84811. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84812. return null;
  84813. }
  84814. var impostors = this._physicsEngine.getImpostors();
  84815. if (impostors.length === 0) {
  84816. return null;
  84817. }
  84818. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84819. event.dispose(false);
  84820. return event;
  84821. };
  84822. /**
  84823. * @param {Vector3} origin the origin of the updraft
  84824. * @param {number} radius the radius of the updraft
  84825. * @param {number} strength the strength of the updraft
  84826. * @param {number} height the height of the updraft
  84827. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84828. */
  84829. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84830. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84831. if (!this._physicsEngine) {
  84832. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84833. return null;
  84834. }
  84835. if (this._physicsEngine.getImpostors().length === 0) {
  84836. return null;
  84837. }
  84838. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84839. event.dispose(false);
  84840. return event;
  84841. };
  84842. /**
  84843. * @param {Vector3} origin the of the vortex
  84844. * @param {number} radius the radius of the vortex
  84845. * @param {number} strength the strength of the vortex
  84846. * @param {number} height the height of the vortex
  84847. */
  84848. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84849. if (!this._physicsEngine) {
  84850. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84851. return null;
  84852. }
  84853. if (this._physicsEngine.getImpostors().length === 0) {
  84854. return null;
  84855. }
  84856. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84857. event.dispose(false);
  84858. return event;
  84859. };
  84860. return PhysicsHelper;
  84861. }());
  84862. BABYLON.PhysicsHelper = PhysicsHelper;
  84863. /***** Radial explosion *****/
  84864. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84865. function PhysicsRadialExplosionEvent(scene) {
  84866. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84867. this._rays = [];
  84868. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84869. this._scene = scene;
  84870. }
  84871. /**
  84872. * Returns the data related to the radial explosion event (sphere & rays).
  84873. * @returns {PhysicsRadialExplosionEventData}
  84874. */
  84875. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84876. this._dataFetched = true;
  84877. return {
  84878. sphere: this._sphere,
  84879. rays: this._rays,
  84880. };
  84881. };
  84882. /**
  84883. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84884. * @param impostor
  84885. * @param {Vector3} origin the origin of the explosion
  84886. * @param {number} radius the explosion radius
  84887. * @param {number} strength the explosion strength
  84888. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84889. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84890. */
  84891. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84892. if (impostor.mass === 0) {
  84893. return null;
  84894. }
  84895. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84896. return null;
  84897. }
  84898. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84899. return null;
  84900. }
  84901. var impostorObjectCenter = impostor.getObjectCenter();
  84902. var direction = impostorObjectCenter.subtract(origin);
  84903. var ray = new BABYLON.Ray(origin, direction, radius);
  84904. this._rays.push(ray);
  84905. var hit = ray.intersectsMesh(impostor.object);
  84906. var contactPoint = hit.pickedPoint;
  84907. if (!contactPoint) {
  84908. return null;
  84909. }
  84910. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84911. if (distanceFromOrigin > radius) {
  84912. return null;
  84913. }
  84914. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84915. ? strength
  84916. : strength * (1 - (distanceFromOrigin / radius));
  84917. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84918. return { force: force, contactPoint: contactPoint };
  84919. };
  84920. /**
  84921. * Disposes the sphere.
  84922. * @param {bolean} force
  84923. */
  84924. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84925. var _this = this;
  84926. if (force === void 0) { force = true; }
  84927. if (force) {
  84928. this._sphere.dispose();
  84929. }
  84930. else {
  84931. setTimeout(function () {
  84932. if (!_this._dataFetched) {
  84933. _this._sphere.dispose();
  84934. }
  84935. }, 0);
  84936. }
  84937. };
  84938. /*** Helpers ***/
  84939. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84940. if (!this._sphere) {
  84941. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84942. this._sphere.isVisible = false;
  84943. }
  84944. };
  84945. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84946. var impostorObject = impostor.object;
  84947. this._prepareSphere();
  84948. this._sphere.position = origin;
  84949. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84950. this._sphere._updateBoundingInfo();
  84951. this._sphere.computeWorldMatrix(true);
  84952. return this._sphere.intersectsMesh(impostorObject, true);
  84953. };
  84954. return PhysicsRadialExplosionEvent;
  84955. }());
  84956. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84957. /***** Gravitational Field *****/
  84958. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84959. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84960. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84961. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84962. this._physicsHelper = physicsHelper;
  84963. this._scene = scene;
  84964. this._origin = origin;
  84965. this._radius = radius;
  84966. this._strength = strength;
  84967. this._falloff = falloff;
  84968. this._tickCallback = this._tick.bind(this);
  84969. }
  84970. /**
  84971. * Returns the data related to the gravitational field event (sphere).
  84972. * @returns {PhysicsGravitationalFieldEventData}
  84973. */
  84974. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84975. this._dataFetched = true;
  84976. return {
  84977. sphere: this._sphere,
  84978. };
  84979. };
  84980. /**
  84981. * Enables the gravitational field.
  84982. */
  84983. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84984. this._tickCallback.call(this);
  84985. this._scene.registerBeforeRender(this._tickCallback);
  84986. };
  84987. /**
  84988. * Disables the gravitational field.
  84989. */
  84990. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84991. this._scene.unregisterBeforeRender(this._tickCallback);
  84992. };
  84993. /**
  84994. * Disposes the sphere.
  84995. * @param {bolean} force
  84996. */
  84997. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84998. var _this = this;
  84999. if (force === void 0) { force = true; }
  85000. if (force) {
  85001. this._sphere.dispose();
  85002. }
  85003. else {
  85004. setTimeout(function () {
  85005. if (!_this._dataFetched) {
  85006. _this._sphere.dispose();
  85007. }
  85008. }, 0);
  85009. }
  85010. };
  85011. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85012. // Since the params won't change, we fetch the event only once
  85013. if (this._sphere) {
  85014. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85015. }
  85016. else {
  85017. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85018. if (radialExplosionEvent) {
  85019. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85020. }
  85021. }
  85022. };
  85023. return PhysicsGravitationalFieldEvent;
  85024. }());
  85025. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85026. /***** Updraft *****/
  85027. var PhysicsUpdraftEvent = /** @class */ (function () {
  85028. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85029. this._scene = _scene;
  85030. this._origin = _origin;
  85031. this._radius = _radius;
  85032. this._strength = _strength;
  85033. this._height = _height;
  85034. this._updraftMode = _updraftMode;
  85035. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85036. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85037. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85038. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85039. this._physicsEngine = this._scene.getPhysicsEngine();
  85040. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85041. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85042. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85043. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85044. }
  85045. this._tickCallback = this._tick.bind(this);
  85046. }
  85047. /**
  85048. * Returns the data related to the updraft event (cylinder).
  85049. * @returns {PhysicsUpdraftEventData}
  85050. */
  85051. PhysicsUpdraftEvent.prototype.getData = function () {
  85052. this._dataFetched = true;
  85053. return {
  85054. cylinder: this._cylinder,
  85055. };
  85056. };
  85057. /**
  85058. * Enables the updraft.
  85059. */
  85060. PhysicsUpdraftEvent.prototype.enable = function () {
  85061. this._tickCallback.call(this);
  85062. this._scene.registerBeforeRender(this._tickCallback);
  85063. };
  85064. /**
  85065. * Disables the cortex.
  85066. */
  85067. PhysicsUpdraftEvent.prototype.disable = function () {
  85068. this._scene.unregisterBeforeRender(this._tickCallback);
  85069. };
  85070. /**
  85071. * Disposes the sphere.
  85072. * @param {bolean} force
  85073. */
  85074. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85075. var _this = this;
  85076. if (force === void 0) { force = true; }
  85077. if (force) {
  85078. this._cylinder.dispose();
  85079. }
  85080. else {
  85081. setTimeout(function () {
  85082. if (!_this._dataFetched) {
  85083. _this._cylinder.dispose();
  85084. }
  85085. }, 0);
  85086. }
  85087. };
  85088. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85089. if (impostor.mass === 0) {
  85090. return null;
  85091. }
  85092. if (!this._intersectsWithCylinder(impostor)) {
  85093. return null;
  85094. }
  85095. var impostorObjectCenter = impostor.getObjectCenter();
  85096. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85097. var direction = this._originDirection;
  85098. }
  85099. else {
  85100. var direction = impostorObjectCenter.subtract(this._originTop);
  85101. }
  85102. var multiplier = this._strength * -1;
  85103. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85104. return { force: force, contactPoint: impostorObjectCenter };
  85105. };
  85106. PhysicsUpdraftEvent.prototype._tick = function () {
  85107. var _this = this;
  85108. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85109. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85110. if (!impostorForceAndContactPoint) {
  85111. return;
  85112. }
  85113. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85114. });
  85115. };
  85116. /*** Helpers ***/
  85117. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85118. if (!this._cylinder) {
  85119. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85120. height: this._height,
  85121. diameter: this._radius * 2,
  85122. }, this._scene);
  85123. this._cylinder.isVisible = false;
  85124. }
  85125. };
  85126. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85127. var impostorObject = impostor.object;
  85128. this._prepareCylinder();
  85129. this._cylinder.position = this._cylinderPosition;
  85130. return this._cylinder.intersectsMesh(impostorObject, true);
  85131. };
  85132. return PhysicsUpdraftEvent;
  85133. }());
  85134. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85135. /***** Vortex *****/
  85136. var PhysicsVortexEvent = /** @class */ (function () {
  85137. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85138. this._scene = _scene;
  85139. this._origin = _origin;
  85140. this._radius = _radius;
  85141. this._strength = _strength;
  85142. this._height = _height;
  85143. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85144. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85145. this._updraftMultiplier = 0.02;
  85146. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85147. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85148. this._physicsEngine = this._scene.getPhysicsEngine();
  85149. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85150. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85151. this._tickCallback = this._tick.bind(this);
  85152. }
  85153. /**
  85154. * Returns the data related to the vortex event (cylinder).
  85155. * @returns {PhysicsVortexEventData}
  85156. */
  85157. PhysicsVortexEvent.prototype.getData = function () {
  85158. this._dataFetched = true;
  85159. return {
  85160. cylinder: this._cylinder,
  85161. };
  85162. };
  85163. /**
  85164. * Enables the vortex.
  85165. */
  85166. PhysicsVortexEvent.prototype.enable = function () {
  85167. this._tickCallback.call(this);
  85168. this._scene.registerBeforeRender(this._tickCallback);
  85169. };
  85170. /**
  85171. * Disables the cortex.
  85172. */
  85173. PhysicsVortexEvent.prototype.disable = function () {
  85174. this._scene.unregisterBeforeRender(this._tickCallback);
  85175. };
  85176. /**
  85177. * Disposes the sphere.
  85178. * @param {bolean} force
  85179. */
  85180. PhysicsVortexEvent.prototype.dispose = function (force) {
  85181. var _this = this;
  85182. if (force === void 0) { force = true; }
  85183. if (force) {
  85184. this._cylinder.dispose();
  85185. }
  85186. else {
  85187. setTimeout(function () {
  85188. if (!_this._dataFetched) {
  85189. _this._cylinder.dispose();
  85190. }
  85191. }, 0);
  85192. }
  85193. };
  85194. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85195. if (impostor.mass === 0) {
  85196. return null;
  85197. }
  85198. if (!this._intersectsWithCylinder(impostor)) {
  85199. return null;
  85200. }
  85201. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85202. return null;
  85203. }
  85204. var impostorObjectCenter = impostor.getObjectCenter();
  85205. 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)
  85206. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85207. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85208. var hit = ray.intersectsMesh(impostor.object);
  85209. var contactPoint = hit.pickedPoint;
  85210. if (!contactPoint) {
  85211. return null;
  85212. }
  85213. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85214. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85215. var directionToOrigin = contactPoint.normalize();
  85216. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85217. directionToOrigin = directionToOrigin.negate();
  85218. }
  85219. // TODO: find a more physically based solution
  85220. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85221. var forceX = directionToOrigin.x * this._strength / 8;
  85222. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85223. var forceZ = directionToOrigin.z * this._strength / 8;
  85224. }
  85225. else {
  85226. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85227. var forceY = this._originTop.y * this._updraftMultiplier;
  85228. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85229. }
  85230. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85231. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85232. return { force: force, contactPoint: impostorObjectCenter };
  85233. };
  85234. PhysicsVortexEvent.prototype._tick = function () {
  85235. var _this = this;
  85236. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85237. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85238. if (!impostorForceAndContactPoint) {
  85239. return;
  85240. }
  85241. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85242. });
  85243. };
  85244. /*** Helpers ***/
  85245. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85246. if (!this._cylinder) {
  85247. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85248. height: this._height,
  85249. diameter: this._radius * 2,
  85250. }, this._scene);
  85251. this._cylinder.isVisible = false;
  85252. }
  85253. };
  85254. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85255. var impostorObject = impostor.object;
  85256. this._prepareCylinder();
  85257. this._cylinder.position = this._cylinderPosition;
  85258. return this._cylinder.intersectsMesh(impostorObject, true);
  85259. };
  85260. return PhysicsVortexEvent;
  85261. }());
  85262. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85263. /***** Enums *****/
  85264. /**
  85265. * The strenght of the force in correspondence to the distance of the affected object
  85266. */
  85267. var PhysicsRadialImpulseFalloff;
  85268. (function (PhysicsRadialImpulseFalloff) {
  85269. /** Defines that impulse is constant in strength across it's whole radius */
  85270. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85271. /** DEfines that impulse gets weaker if it's further from the origin */
  85272. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85273. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85274. /**
  85275. * The strenght of the force in correspondence to the distance of the affected object
  85276. */
  85277. var PhysicsUpdraftMode;
  85278. (function (PhysicsUpdraftMode) {
  85279. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85280. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85281. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85282. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85283. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85284. })(BABYLON || (BABYLON = {}));
  85285. //# sourceMappingURL=babylon.physicsHelper.js.map
  85286. var BABYLON;
  85287. (function (BABYLON) {
  85288. var CannonJSPlugin = /** @class */ (function () {
  85289. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85290. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85291. if (iterations === void 0) { iterations = 10; }
  85292. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85293. this.name = "CannonJSPlugin";
  85294. this._physicsMaterials = new Array();
  85295. this._fixedTimeStep = 1 / 60;
  85296. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85297. this.BJSCANNON = CANNON;
  85298. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85299. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85300. this._tmpPosition = BABYLON.Vector3.Zero();
  85301. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85302. this._tmpUnityRotation = new BABYLON.Quaternion();
  85303. if (!this.isSupported()) {
  85304. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85305. return;
  85306. }
  85307. this._extendNamespace();
  85308. this.world = new this.BJSCANNON.World();
  85309. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85310. this.world.solver.iterations = iterations;
  85311. }
  85312. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85313. this.world.gravity.copy(gravity);
  85314. };
  85315. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85316. this._fixedTimeStep = timeStep;
  85317. };
  85318. CannonJSPlugin.prototype.getTimeStep = function () {
  85319. return this._fixedTimeStep;
  85320. };
  85321. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85322. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85323. };
  85324. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85325. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85326. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85327. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85328. };
  85329. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85330. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85331. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85332. impostor.physicsBody.applyForce(impulse, worldPoint);
  85333. };
  85334. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85335. //parent-child relationship. Does this impostor has a parent impostor?
  85336. if (impostor.parent) {
  85337. if (impostor.physicsBody) {
  85338. this.removePhysicsBody(impostor);
  85339. //TODO is that needed?
  85340. impostor.forceUpdate();
  85341. }
  85342. return;
  85343. }
  85344. //should a new body be created for this impostor?
  85345. if (impostor.isBodyInitRequired()) {
  85346. var shape = this._createShape(impostor);
  85347. //unregister events, if body is being changed
  85348. var oldBody = impostor.physicsBody;
  85349. if (oldBody) {
  85350. this.removePhysicsBody(impostor);
  85351. }
  85352. //create the body and material
  85353. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85354. var bodyCreationObject = {
  85355. mass: impostor.getParam("mass"),
  85356. material: material
  85357. };
  85358. // A simple extend, in case native options were used.
  85359. var nativeOptions = impostor.getParam("nativeOptions");
  85360. for (var key in nativeOptions) {
  85361. if (nativeOptions.hasOwnProperty(key)) {
  85362. bodyCreationObject[key] = nativeOptions[key];
  85363. }
  85364. }
  85365. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85366. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85367. this.world.addEventListener("preStep", impostor.beforeStep);
  85368. this.world.addEventListener("postStep", impostor.afterStep);
  85369. impostor.physicsBody.addShape(shape);
  85370. this.world.add(impostor.physicsBody);
  85371. //try to keep the body moving in the right direction by taking old properties.
  85372. //Should be tested!
  85373. if (oldBody) {
  85374. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85375. impostor.physicsBody[param].copy(oldBody[param]);
  85376. });
  85377. }
  85378. this._processChildMeshes(impostor);
  85379. }
  85380. //now update the body's transformation
  85381. this._updatePhysicsBodyTransformation(impostor);
  85382. };
  85383. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85384. var _this = this;
  85385. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85386. var currentRotation = mainImpostor.object.rotationQuaternion;
  85387. if (meshChildren.length) {
  85388. var processMesh = function (localPosition, mesh) {
  85389. if (!currentRotation || !mesh.rotationQuaternion) {
  85390. return;
  85391. }
  85392. var childImpostor = mesh.getPhysicsImpostor();
  85393. if (childImpostor) {
  85394. var parent = childImpostor.parent;
  85395. if (parent !== mainImpostor) {
  85396. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85397. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85398. if (childImpostor.physicsBody) {
  85399. _this.removePhysicsBody(childImpostor);
  85400. childImpostor.physicsBody = null;
  85401. }
  85402. childImpostor.parent = mainImpostor;
  85403. childImpostor.resetUpdateFlags();
  85404. 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));
  85405. //Add the mass of the children.
  85406. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85407. }
  85408. }
  85409. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85410. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85411. };
  85412. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85413. }
  85414. };
  85415. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85416. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85417. this.world.removeEventListener("preStep", impostor.beforeStep);
  85418. this.world.removeEventListener("postStep", impostor.afterStep);
  85419. this.world.remove(impostor.physicsBody);
  85420. };
  85421. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85422. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85423. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85424. if (!mainBody || !connectedBody) {
  85425. return;
  85426. }
  85427. var constraint;
  85428. var jointData = impostorJoint.joint.jointData;
  85429. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85430. var constraintData = {
  85431. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85432. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85433. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85434. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85435. maxForce: jointData.nativeParams.maxForce,
  85436. collideConnected: !!jointData.collision
  85437. };
  85438. switch (impostorJoint.joint.type) {
  85439. case BABYLON.PhysicsJoint.HingeJoint:
  85440. case BABYLON.PhysicsJoint.Hinge2Joint:
  85441. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85442. break;
  85443. case BABYLON.PhysicsJoint.DistanceJoint:
  85444. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85445. break;
  85446. case BABYLON.PhysicsJoint.SpringJoint:
  85447. var springData = jointData;
  85448. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85449. restLength: springData.length,
  85450. stiffness: springData.stiffness,
  85451. damping: springData.damping,
  85452. localAnchorA: constraintData.pivotA,
  85453. localAnchorB: constraintData.pivotB
  85454. });
  85455. break;
  85456. case BABYLON.PhysicsJoint.LockJoint:
  85457. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85458. break;
  85459. case BABYLON.PhysicsJoint.PointToPointJoint:
  85460. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85461. default:
  85462. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85463. break;
  85464. }
  85465. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85466. constraint.collideConnected = !!jointData.collision;
  85467. impostorJoint.joint.physicsJoint = constraint;
  85468. //don't add spring as constraint, as it is not one.
  85469. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85470. this.world.addConstraint(constraint);
  85471. }
  85472. else {
  85473. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85474. constraint.applyForce();
  85475. });
  85476. }
  85477. };
  85478. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85479. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85480. };
  85481. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85482. var index;
  85483. var mat;
  85484. for (index = 0; index < this._physicsMaterials.length; index++) {
  85485. mat = this._physicsMaterials[index];
  85486. if (mat.friction === friction && mat.restitution === restitution) {
  85487. return mat;
  85488. }
  85489. }
  85490. var currentMat = new this.BJSCANNON.Material(name);
  85491. currentMat.friction = friction;
  85492. currentMat.restitution = restitution;
  85493. this._physicsMaterials.push(currentMat);
  85494. return currentMat;
  85495. };
  85496. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85497. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85498. };
  85499. CannonJSPlugin.prototype._createShape = function (impostor) {
  85500. var object = impostor.object;
  85501. var returnValue;
  85502. var extendSize = impostor.getObjectExtendSize();
  85503. switch (impostor.type) {
  85504. case BABYLON.PhysicsImpostor.SphereImpostor:
  85505. var radiusX = extendSize.x;
  85506. var radiusY = extendSize.y;
  85507. var radiusZ = extendSize.z;
  85508. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85509. break;
  85510. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85511. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85512. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85513. break;
  85514. case BABYLON.PhysicsImpostor.BoxImpostor:
  85515. var box = extendSize.scale(0.5);
  85516. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85517. break;
  85518. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85519. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85520. returnValue = new this.BJSCANNON.Plane();
  85521. break;
  85522. case BABYLON.PhysicsImpostor.MeshImpostor:
  85523. // should transform the vertex data to world coordinates!!
  85524. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85525. var rawFaces = object.getIndices ? object.getIndices() : [];
  85526. if (!rawVerts)
  85527. return;
  85528. // get only scale! so the object could transform correctly.
  85529. var oldPosition = object.position.clone();
  85530. var oldRotation = object.rotation && object.rotation.clone();
  85531. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85532. object.position.copyFromFloats(0, 0, 0);
  85533. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85534. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85535. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85536. var transform = object.computeWorldMatrix(true);
  85537. // convert rawVerts to object space
  85538. var temp = new Array();
  85539. var index;
  85540. for (index = 0; index < rawVerts.length; index += 3) {
  85541. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85542. }
  85543. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85544. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85545. //now set back the transformation!
  85546. object.position.copyFrom(oldPosition);
  85547. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85548. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85549. break;
  85550. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85551. var oldPosition2 = object.position.clone();
  85552. var oldRotation2 = object.rotation && object.rotation.clone();
  85553. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85554. object.position.copyFromFloats(0, 0, 0);
  85555. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85556. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85557. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85558. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85559. returnValue = this._createHeightmap(object);
  85560. object.position.copyFrom(oldPosition2);
  85561. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85562. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85563. object.computeWorldMatrix(true);
  85564. break;
  85565. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85566. returnValue = new this.BJSCANNON.Particle();
  85567. break;
  85568. }
  85569. return returnValue;
  85570. };
  85571. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85572. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85573. var transform = object.computeWorldMatrix(true);
  85574. // convert rawVerts to object space
  85575. var temp = new Array();
  85576. var index;
  85577. for (index = 0; index < pos.length; index += 3) {
  85578. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85579. }
  85580. pos = temp;
  85581. var matrix = new Array();
  85582. //For now pointDepth will not be used and will be automatically calculated.
  85583. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85584. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85585. var boundingInfo = object.getBoundingInfo();
  85586. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85587. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85588. var elementSize = dim * 2 / arraySize;
  85589. for (var i = 0; i < pos.length; i = i + 3) {
  85590. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85591. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85592. var y = -pos[i + 2] + minY;
  85593. if (!matrix[x]) {
  85594. matrix[x] = [];
  85595. }
  85596. if (!matrix[x][z]) {
  85597. matrix[x][z] = y;
  85598. }
  85599. matrix[x][z] = Math.max(y, matrix[x][z]);
  85600. }
  85601. for (var x = 0; x <= arraySize; ++x) {
  85602. if (!matrix[x]) {
  85603. var loc = 1;
  85604. while (!matrix[(x + loc) % arraySize]) {
  85605. loc++;
  85606. }
  85607. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85608. //console.log("missing x", x);
  85609. }
  85610. for (var z = 0; z <= arraySize; ++z) {
  85611. if (!matrix[x][z]) {
  85612. var loc = 1;
  85613. var newValue;
  85614. while (newValue === undefined) {
  85615. newValue = matrix[x][(z + loc++) % arraySize];
  85616. }
  85617. matrix[x][z] = newValue;
  85618. }
  85619. }
  85620. }
  85621. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85622. elementSize: elementSize
  85623. });
  85624. //For future reference, needed for body transformation
  85625. shape.minY = minY;
  85626. return shape;
  85627. };
  85628. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85629. var object = impostor.object;
  85630. //make sure it is updated...
  85631. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85632. // The delta between the mesh position and the mesh bounding box center
  85633. var bInfo = object.getBoundingInfo();
  85634. if (!bInfo)
  85635. return;
  85636. var center = impostor.getObjectCenter();
  85637. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85638. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85639. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85640. this._tmpPosition.copyFrom(center);
  85641. var quaternion = object.rotationQuaternion;
  85642. if (!quaternion) {
  85643. return;
  85644. }
  85645. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85646. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85647. //-90 DEG in X, precalculated
  85648. quaternion = quaternion.multiply(this._minus90X);
  85649. //Invert! (Precalculated, 90 deg in X)
  85650. //No need to clone. this will never change.
  85651. impostor.setDeltaRotation(this._plus90X);
  85652. }
  85653. //If it is a heightfield, if should be centered.
  85654. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  85655. var mesh = object;
  85656. var boundingInfo = mesh.getBoundingInfo();
  85657. //calculate the correct body position:
  85658. var rotationQuaternion = mesh.rotationQuaternion;
  85659. mesh.rotationQuaternion = this._tmpUnityRotation;
  85660. mesh.computeWorldMatrix(true);
  85661. //get original center with no rotation
  85662. var c = center.clone();
  85663. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  85664. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  85665. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  85666. mesh.setPreTransformMatrix(p);
  85667. mesh.computeWorldMatrix(true);
  85668. //calculate the translation
  85669. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  85670. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  85671. //add it inverted to the delta
  85672. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  85673. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  85674. //rotation is back
  85675. mesh.rotationQuaternion = rotationQuaternion;
  85676. mesh.setPreTransformMatrix(oldPivot);
  85677. mesh.computeWorldMatrix(true);
  85678. }
  85679. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  85680. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  85681. //this._tmpPosition.copyFrom(object.position);
  85682. }
  85683. impostor.setDeltaPosition(this._tmpDeltaPosition);
  85684. //Now update the impostor object
  85685. impostor.physicsBody.position.copy(this._tmpPosition);
  85686. impostor.physicsBody.quaternion.copy(quaternion);
  85687. };
  85688. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85689. impostor.object.position.copyFrom(impostor.physicsBody.position);
  85690. if (impostor.object.rotationQuaternion) {
  85691. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  85692. }
  85693. };
  85694. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85695. impostor.physicsBody.position.copy(newPosition);
  85696. impostor.physicsBody.quaternion.copy(newRotation);
  85697. };
  85698. CannonJSPlugin.prototype.isSupported = function () {
  85699. return this.BJSCANNON !== undefined;
  85700. };
  85701. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85702. impostor.physicsBody.velocity.copy(velocity);
  85703. };
  85704. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85705. impostor.physicsBody.angularVelocity.copy(velocity);
  85706. };
  85707. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85708. var v = impostor.physicsBody.velocity;
  85709. if (!v) {
  85710. return null;
  85711. }
  85712. return new BABYLON.Vector3(v.x, v.y, v.z);
  85713. };
  85714. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85715. var v = impostor.physicsBody.angularVelocity;
  85716. if (!v) {
  85717. return null;
  85718. }
  85719. return new BABYLON.Vector3(v.x, v.y, v.z);
  85720. };
  85721. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85722. impostor.physicsBody.mass = mass;
  85723. impostor.physicsBody.updateMassProperties();
  85724. };
  85725. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  85726. return impostor.physicsBody.mass;
  85727. };
  85728. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  85729. return impostor.physicsBody.material.friction;
  85730. };
  85731. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85732. impostor.physicsBody.material.friction = friction;
  85733. };
  85734. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85735. return impostor.physicsBody.material.restitution;
  85736. };
  85737. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85738. impostor.physicsBody.material.restitution = restitution;
  85739. };
  85740. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  85741. impostor.physicsBody.sleep();
  85742. };
  85743. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  85744. impostor.physicsBody.wakeUp();
  85745. };
  85746. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85747. joint.physicsJoint.distance = maxDistance;
  85748. };
  85749. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85750. // if (!motorIndex) {
  85751. // joint.physicsJoint.enableMotor();
  85752. // }
  85753. // }
  85754. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85755. // if (!motorIndex) {
  85756. // joint.physicsJoint.disableMotor();
  85757. // }
  85758. // }
  85759. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85760. if (!motorIndex) {
  85761. joint.physicsJoint.enableMotor();
  85762. joint.physicsJoint.setMotorSpeed(speed);
  85763. if (maxForce) {
  85764. this.setLimit(joint, maxForce);
  85765. }
  85766. }
  85767. };
  85768. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85769. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85770. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85771. };
  85772. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85773. var body = impostor.physicsBody;
  85774. mesh.position.x = body.position.x;
  85775. mesh.position.y = body.position.y;
  85776. mesh.position.z = body.position.z;
  85777. if (mesh.rotationQuaternion) {
  85778. mesh.rotationQuaternion.x = body.quaternion.x;
  85779. mesh.rotationQuaternion.y = body.quaternion.y;
  85780. mesh.rotationQuaternion.z = body.quaternion.z;
  85781. mesh.rotationQuaternion.w = body.quaternion.w;
  85782. }
  85783. };
  85784. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85785. var shape = impostor.physicsBody.shapes[0];
  85786. return shape.boundingSphereRadius;
  85787. };
  85788. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85789. var shape = impostor.physicsBody.shapes[0];
  85790. result.x = shape.halfExtents.x * 2;
  85791. result.y = shape.halfExtents.y * 2;
  85792. result.z = shape.halfExtents.z * 2;
  85793. };
  85794. CannonJSPlugin.prototype.dispose = function () {
  85795. };
  85796. CannonJSPlugin.prototype._extendNamespace = function () {
  85797. //this will force cannon to execute at least one step when using interpolation
  85798. var step_tmp1 = new this.BJSCANNON.Vec3();
  85799. var Engine = this.BJSCANNON;
  85800. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85801. maxSubSteps = maxSubSteps || 10;
  85802. timeSinceLastCalled = timeSinceLastCalled || 0;
  85803. if (timeSinceLastCalled === 0) {
  85804. this.internalStep(dt);
  85805. this.time += dt;
  85806. }
  85807. else {
  85808. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85809. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85810. var t0 = performance.now();
  85811. for (var i = 0; i !== internalSteps; i++) {
  85812. this.internalStep(dt);
  85813. if (performance.now() - t0 > dt * 1000) {
  85814. break;
  85815. }
  85816. }
  85817. this.time += timeSinceLastCalled;
  85818. var h = this.time % dt;
  85819. var h_div_dt = h / dt;
  85820. var interpvelo = step_tmp1;
  85821. var bodies = this.bodies;
  85822. for (var j = 0; j !== bodies.length; j++) {
  85823. var b = bodies[j];
  85824. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85825. b.position.vsub(b.previousPosition, interpvelo);
  85826. interpvelo.scale(h_div_dt, interpvelo);
  85827. b.position.vadd(interpvelo, b.interpolatedPosition);
  85828. }
  85829. else {
  85830. b.interpolatedPosition.copy(b.position);
  85831. b.interpolatedQuaternion.copy(b.quaternion);
  85832. }
  85833. }
  85834. }
  85835. };
  85836. };
  85837. return CannonJSPlugin;
  85838. }());
  85839. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85840. })(BABYLON || (BABYLON = {}));
  85841. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85842. var BABYLON;
  85843. (function (BABYLON) {
  85844. var OimoJSPlugin = /** @class */ (function () {
  85845. function OimoJSPlugin(iterations) {
  85846. this.name = "OimoJSPlugin";
  85847. this._tmpImpostorsArray = [];
  85848. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85849. this.BJSOIMO = OIMO;
  85850. this.world = new this.BJSOIMO.World({
  85851. iterations: iterations
  85852. });
  85853. this.world.clear();
  85854. }
  85855. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85856. this.world.gravity.copy(gravity);
  85857. };
  85858. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85859. this.world.timeStep = timeStep;
  85860. };
  85861. OimoJSPlugin.prototype.getTimeStep = function () {
  85862. return this.world.timeStep;
  85863. };
  85864. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85865. var _this = this;
  85866. impostors.forEach(function (impostor) {
  85867. impostor.beforeStep();
  85868. });
  85869. this.world.step();
  85870. impostors.forEach(function (impostor) {
  85871. impostor.afterStep();
  85872. //update the ordered impostors array
  85873. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85874. });
  85875. //check for collisions
  85876. var contact = this.world.contacts;
  85877. while (contact !== null) {
  85878. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85879. contact = contact.next;
  85880. continue;
  85881. }
  85882. //is this body colliding with any other? get the impostor
  85883. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85884. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85885. if (!mainImpostor || !collidingImpostor) {
  85886. contact = contact.next;
  85887. continue;
  85888. }
  85889. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85890. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85891. contact = contact.next;
  85892. }
  85893. };
  85894. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85895. var mass = impostor.physicsBody.mass;
  85896. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85897. };
  85898. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85899. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85900. this.applyImpulse(impostor, force, contactPoint);
  85901. };
  85902. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85903. var _this = this;
  85904. //parent-child relationship. Does this impostor has a parent impostor?
  85905. if (impostor.parent) {
  85906. if (impostor.physicsBody) {
  85907. this.removePhysicsBody(impostor);
  85908. //TODO is that needed?
  85909. impostor.forceUpdate();
  85910. }
  85911. return;
  85912. }
  85913. if (impostor.isBodyInitRequired()) {
  85914. var bodyConfig = {
  85915. name: impostor.uniqueId,
  85916. //Oimo must have mass, also for static objects.
  85917. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85918. size: [],
  85919. type: [],
  85920. pos: [],
  85921. posShape: [],
  85922. rot: [],
  85923. rotShape: [],
  85924. move: impostor.getParam("mass") !== 0,
  85925. density: impostor.getParam("mass"),
  85926. friction: impostor.getParam("friction"),
  85927. restitution: impostor.getParam("restitution"),
  85928. //Supporting older versions of Oimo
  85929. world: this.world
  85930. };
  85931. var impostors = [impostor];
  85932. var addToArray = function (parent) {
  85933. if (!parent.getChildMeshes)
  85934. return;
  85935. parent.getChildMeshes().forEach(function (m) {
  85936. if (m.physicsImpostor) {
  85937. impostors.push(m.physicsImpostor);
  85938. //m.physicsImpostor._init();
  85939. }
  85940. });
  85941. };
  85942. addToArray(impostor.object);
  85943. var checkWithEpsilon_1 = function (value) {
  85944. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85945. };
  85946. impostors.forEach(function (i) {
  85947. if (!i.object.rotationQuaternion) {
  85948. return;
  85949. }
  85950. //get the correct bounding box
  85951. var oldQuaternion = i.object.rotationQuaternion;
  85952. var rot = oldQuaternion.toEulerAngles();
  85953. var extendSize = i.getObjectExtendSize();
  85954. var radToDeg = 57.295779513082320876;
  85955. if (i === impostor) {
  85956. var center = impostor.getObjectCenter();
  85957. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85958. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85959. //Can also use Array.prototype.push.apply
  85960. bodyConfig.pos.push(center.x);
  85961. bodyConfig.pos.push(center.y);
  85962. bodyConfig.pos.push(center.z);
  85963. bodyConfig.posShape.push(0, 0, 0);
  85964. //tmp solution
  85965. bodyConfig.rot.push(rot.x * radToDeg);
  85966. bodyConfig.rot.push(rot.y * radToDeg);
  85967. bodyConfig.rot.push(rot.z * radToDeg);
  85968. bodyConfig.rotShape.push(0, 0, 0);
  85969. }
  85970. else {
  85971. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85972. bodyConfig.posShape.push(localPosition.x);
  85973. bodyConfig.posShape.push(localPosition.y);
  85974. bodyConfig.posShape.push(localPosition.z);
  85975. bodyConfig.pos.push(0, 0, 0);
  85976. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85977. bodyConfig.rot.push(0);
  85978. bodyConfig.rot.push(0);
  85979. bodyConfig.rot.push(0);
  85980. bodyConfig.rotShape.push(rot.x * radToDeg);
  85981. bodyConfig.rotShape.push(rot.y * radToDeg);
  85982. bodyConfig.rotShape.push(rot.z * radToDeg);
  85983. }
  85984. // register mesh
  85985. switch (i.type) {
  85986. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85987. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85988. case BABYLON.PhysicsImpostor.SphereImpostor:
  85989. var radiusX = extendSize.x;
  85990. var radiusY = extendSize.y;
  85991. var radiusZ = extendSize.z;
  85992. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85993. bodyConfig.type.push('sphere');
  85994. //due to the way oimo works with compounds, add 3 times
  85995. bodyConfig.size.push(size);
  85996. bodyConfig.size.push(size);
  85997. bodyConfig.size.push(size);
  85998. break;
  85999. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86000. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86001. var sizeY = checkWithEpsilon_1(extendSize.y);
  86002. bodyConfig.type.push('cylinder');
  86003. bodyConfig.size.push(sizeX);
  86004. bodyConfig.size.push(sizeY);
  86005. //due to the way oimo works with compounds, add one more value.
  86006. bodyConfig.size.push(sizeY);
  86007. break;
  86008. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86009. case BABYLON.PhysicsImpostor.BoxImpostor:
  86010. default:
  86011. var sizeX = checkWithEpsilon_1(extendSize.x);
  86012. var sizeY = checkWithEpsilon_1(extendSize.y);
  86013. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86014. bodyConfig.type.push('box');
  86015. //if (i === impostor) {
  86016. bodyConfig.size.push(sizeX);
  86017. bodyConfig.size.push(sizeY);
  86018. bodyConfig.size.push(sizeZ);
  86019. //} else {
  86020. // bodyConfig.size.push(0,0,0);
  86021. //}
  86022. break;
  86023. }
  86024. //actually not needed, but hey...
  86025. i.object.rotationQuaternion = oldQuaternion;
  86026. });
  86027. impostor.physicsBody = this.world.add(bodyConfig);
  86028. }
  86029. else {
  86030. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86031. }
  86032. impostor.setDeltaPosition(this._tmpPositionVector);
  86033. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86034. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86035. };
  86036. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86037. //impostor.physicsBody.dispose();
  86038. //Same as : (older oimo versions)
  86039. this.world.removeRigidBody(impostor.physicsBody);
  86040. };
  86041. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86042. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86043. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86044. if (!mainBody || !connectedBody) {
  86045. return;
  86046. }
  86047. var jointData = impostorJoint.joint.jointData;
  86048. var options = jointData.nativeParams || {};
  86049. var type;
  86050. var nativeJointData = {
  86051. body1: mainBody,
  86052. body2: connectedBody,
  86053. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86054. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86055. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86056. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86057. min: options.min,
  86058. max: options.max,
  86059. collision: options.collision || jointData.collision,
  86060. spring: options.spring,
  86061. //supporting older version of Oimo
  86062. world: this.world
  86063. };
  86064. switch (impostorJoint.joint.type) {
  86065. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86066. type = "jointBall";
  86067. break;
  86068. case BABYLON.PhysicsJoint.SpringJoint:
  86069. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86070. var springData = jointData;
  86071. nativeJointData.min = springData.length || nativeJointData.min;
  86072. //Max should also be set, just make sure it is at least min
  86073. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86074. case BABYLON.PhysicsJoint.DistanceJoint:
  86075. type = "jointDistance";
  86076. nativeJointData.max = jointData.maxDistance;
  86077. break;
  86078. case BABYLON.PhysicsJoint.PrismaticJoint:
  86079. type = "jointPrisme";
  86080. break;
  86081. case BABYLON.PhysicsJoint.SliderJoint:
  86082. type = "jointSlide";
  86083. break;
  86084. case BABYLON.PhysicsJoint.WheelJoint:
  86085. type = "jointWheel";
  86086. break;
  86087. case BABYLON.PhysicsJoint.HingeJoint:
  86088. default:
  86089. type = "jointHinge";
  86090. break;
  86091. }
  86092. nativeJointData.type = type;
  86093. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86094. };
  86095. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86096. //Bug in Oimo prevents us from disposing a joint in the playground
  86097. //joint.joint.physicsJoint.dispose();
  86098. //So we will bruteforce it!
  86099. try {
  86100. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86101. }
  86102. catch (e) {
  86103. BABYLON.Tools.Warn(e);
  86104. }
  86105. };
  86106. OimoJSPlugin.prototype.isSupported = function () {
  86107. return this.BJSOIMO !== undefined;
  86108. };
  86109. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86110. if (!impostor.physicsBody.sleeping) {
  86111. //TODO check that
  86112. /*if (impostor.physicsBody.shapes.next) {
  86113. var parentShape = this._getLastShape(impostor.physicsBody);
  86114. impostor.object.position.copyFrom(parentShape.position);
  86115. console.log(parentShape.position);
  86116. } else {*/
  86117. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86118. //}
  86119. if (impostor.object.rotationQuaternion) {
  86120. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86121. }
  86122. }
  86123. };
  86124. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86125. var body = impostor.physicsBody;
  86126. body.position.copy(newPosition);
  86127. body.orientation.copy(newRotation);
  86128. body.syncShapes();
  86129. body.awake();
  86130. };
  86131. /*private _getLastShape(body: any): any {
  86132. var lastShape = body.shapes;
  86133. while (lastShape.next) {
  86134. lastShape = lastShape.next;
  86135. }
  86136. return lastShape;
  86137. }*/
  86138. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86139. impostor.physicsBody.linearVelocity.copy(velocity);
  86140. };
  86141. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86142. impostor.physicsBody.angularVelocity.copy(velocity);
  86143. };
  86144. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86145. var v = impostor.physicsBody.linearVelocity;
  86146. if (!v) {
  86147. return null;
  86148. }
  86149. return new BABYLON.Vector3(v.x, v.y, v.z);
  86150. };
  86151. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86152. var v = impostor.physicsBody.angularVelocity;
  86153. if (!v) {
  86154. return null;
  86155. }
  86156. return new BABYLON.Vector3(v.x, v.y, v.z);
  86157. };
  86158. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86159. var staticBody = mass === 0;
  86160. //this will actually set the body's density and not its mass.
  86161. //But this is how oimo treats the mass variable.
  86162. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86163. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86164. };
  86165. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86166. return impostor.physicsBody.shapes.density;
  86167. };
  86168. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86169. return impostor.physicsBody.shapes.friction;
  86170. };
  86171. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86172. impostor.physicsBody.shapes.friction = friction;
  86173. };
  86174. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86175. return impostor.physicsBody.shapes.restitution;
  86176. };
  86177. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86178. impostor.physicsBody.shapes.restitution = restitution;
  86179. };
  86180. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86181. impostor.physicsBody.sleep();
  86182. };
  86183. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86184. impostor.physicsBody.awake();
  86185. };
  86186. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86187. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86188. if (minDistance !== void 0) {
  86189. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86190. }
  86191. };
  86192. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86193. //TODO separate rotational and transational motors.
  86194. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86195. if (motor) {
  86196. motor.setMotor(speed, maxForce);
  86197. }
  86198. };
  86199. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86200. //TODO separate rotational and transational motors.
  86201. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86202. if (motor) {
  86203. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86204. }
  86205. };
  86206. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86207. var body = impostor.physicsBody;
  86208. mesh.position.x = body.position.x;
  86209. mesh.position.y = body.position.y;
  86210. mesh.position.z = body.position.z;
  86211. if (mesh.rotationQuaternion) {
  86212. mesh.rotationQuaternion.x = body.orientation.x;
  86213. mesh.rotationQuaternion.y = body.orientation.y;
  86214. mesh.rotationQuaternion.z = body.orientation.z;
  86215. mesh.rotationQuaternion.w = body.orientation.s;
  86216. }
  86217. };
  86218. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86219. return impostor.physicsBody.shapes.radius;
  86220. };
  86221. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86222. var shape = impostor.physicsBody.shapes;
  86223. result.x = shape.halfWidth * 2;
  86224. result.y = shape.halfHeight * 2;
  86225. result.z = shape.halfDepth * 2;
  86226. };
  86227. OimoJSPlugin.prototype.dispose = function () {
  86228. this.world.clear();
  86229. };
  86230. return OimoJSPlugin;
  86231. }());
  86232. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86233. })(BABYLON || (BABYLON = {}));
  86234. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86235. var BABYLON;
  86236. (function (BABYLON) {
  86237. /*
  86238. * Based on jsTGALoader - Javascript loader for TGA file
  86239. * By Vincent Thibault
  86240. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86241. */
  86242. var TGATools = /** @class */ (function () {
  86243. function TGATools() {
  86244. }
  86245. TGATools.GetTGAHeader = function (data) {
  86246. var offset = 0;
  86247. var header = {
  86248. id_length: data[offset++],
  86249. colormap_type: data[offset++],
  86250. image_type: data[offset++],
  86251. colormap_index: data[offset++] | data[offset++] << 8,
  86252. colormap_length: data[offset++] | data[offset++] << 8,
  86253. colormap_size: data[offset++],
  86254. origin: [
  86255. data[offset++] | data[offset++] << 8,
  86256. data[offset++] | data[offset++] << 8
  86257. ],
  86258. width: data[offset++] | data[offset++] << 8,
  86259. height: data[offset++] | data[offset++] << 8,
  86260. pixel_size: data[offset++],
  86261. flags: data[offset++]
  86262. };
  86263. return header;
  86264. };
  86265. TGATools.UploadContent = function (gl, data) {
  86266. // Not enough data to contain header ?
  86267. if (data.length < 19) {
  86268. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86269. return;
  86270. }
  86271. // Read Header
  86272. var offset = 18;
  86273. var header = TGATools.GetTGAHeader(data);
  86274. // Assume it's a valid Targa file.
  86275. if (header.id_length + offset > data.length) {
  86276. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86277. return;
  86278. }
  86279. // Skip not needed data
  86280. offset += header.id_length;
  86281. var use_rle = false;
  86282. var use_pal = false;
  86283. var use_grey = false;
  86284. // Get some informations.
  86285. switch (header.image_type) {
  86286. case TGATools._TYPE_RLE_INDEXED:
  86287. use_rle = true;
  86288. case TGATools._TYPE_INDEXED:
  86289. use_pal = true;
  86290. break;
  86291. case TGATools._TYPE_RLE_RGB:
  86292. use_rle = true;
  86293. case TGATools._TYPE_RGB:
  86294. // use_rgb = true;
  86295. break;
  86296. case TGATools._TYPE_RLE_GREY:
  86297. use_rle = true;
  86298. case TGATools._TYPE_GREY:
  86299. use_grey = true;
  86300. break;
  86301. }
  86302. var pixel_data;
  86303. // var numAlphaBits = header.flags & 0xf;
  86304. var pixel_size = header.pixel_size >> 3;
  86305. var pixel_total = header.width * header.height * pixel_size;
  86306. // Read palettes
  86307. var palettes;
  86308. if (use_pal) {
  86309. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86310. }
  86311. // Read LRE
  86312. if (use_rle) {
  86313. pixel_data = new Uint8Array(pixel_total);
  86314. var c, count, i;
  86315. var localOffset = 0;
  86316. var pixels = new Uint8Array(pixel_size);
  86317. while (offset < pixel_total && localOffset < pixel_total) {
  86318. c = data[offset++];
  86319. count = (c & 0x7f) + 1;
  86320. // RLE pixels
  86321. if (c & 0x80) {
  86322. // Bind pixel tmp array
  86323. for (i = 0; i < pixel_size; ++i) {
  86324. pixels[i] = data[offset++];
  86325. }
  86326. // Copy pixel array
  86327. for (i = 0; i < count; ++i) {
  86328. pixel_data.set(pixels, localOffset + i * pixel_size);
  86329. }
  86330. localOffset += pixel_size * count;
  86331. }
  86332. // Raw pixels
  86333. else {
  86334. count *= pixel_size;
  86335. for (i = 0; i < count; ++i) {
  86336. pixel_data[localOffset + i] = data[offset++];
  86337. }
  86338. localOffset += count;
  86339. }
  86340. }
  86341. }
  86342. // RAW Pixels
  86343. else {
  86344. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86345. }
  86346. // Load to texture
  86347. var x_start, y_start, x_step, y_step, y_end, x_end;
  86348. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86349. default:
  86350. case TGATools._ORIGIN_UL:
  86351. x_start = 0;
  86352. x_step = 1;
  86353. x_end = header.width;
  86354. y_start = 0;
  86355. y_step = 1;
  86356. y_end = header.height;
  86357. break;
  86358. case TGATools._ORIGIN_BL:
  86359. x_start = 0;
  86360. x_step = 1;
  86361. x_end = header.width;
  86362. y_start = header.height - 1;
  86363. y_step = -1;
  86364. y_end = -1;
  86365. break;
  86366. case TGATools._ORIGIN_UR:
  86367. x_start = header.width - 1;
  86368. x_step = -1;
  86369. x_end = -1;
  86370. y_start = 0;
  86371. y_step = 1;
  86372. y_end = header.height;
  86373. break;
  86374. case TGATools._ORIGIN_BR:
  86375. x_start = header.width - 1;
  86376. x_step = -1;
  86377. x_end = -1;
  86378. y_start = header.height - 1;
  86379. y_step = -1;
  86380. y_end = -1;
  86381. break;
  86382. }
  86383. // Load the specify method
  86384. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86385. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86386. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86387. };
  86388. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86389. var image = pixel_data, colormap = palettes;
  86390. var width = header.width, height = header.height;
  86391. var color, i = 0, x, y;
  86392. var imageData = new Uint8Array(width * height * 4);
  86393. for (y = y_start; y !== y_end; y += y_step) {
  86394. for (x = x_start; x !== x_end; x += x_step, i++) {
  86395. color = image[i];
  86396. imageData[(x + width * y) * 4 + 3] = 255;
  86397. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86398. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86399. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86400. }
  86401. }
  86402. return imageData;
  86403. };
  86404. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86405. var image = pixel_data;
  86406. var width = header.width, height = header.height;
  86407. var color, i = 0, x, y;
  86408. var imageData = new Uint8Array(width * height * 4);
  86409. for (y = y_start; y !== y_end; y += y_step) {
  86410. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86411. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86412. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86413. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86414. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86415. imageData[(x + width * y) * 4 + 0] = r;
  86416. imageData[(x + width * y) * 4 + 1] = g;
  86417. imageData[(x + width * y) * 4 + 2] = b;
  86418. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86419. }
  86420. }
  86421. return imageData;
  86422. };
  86423. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86424. var image = pixel_data;
  86425. var width = header.width, height = header.height;
  86426. var i = 0, x, y;
  86427. var imageData = new Uint8Array(width * height * 4);
  86428. for (y = y_start; y !== y_end; y += y_step) {
  86429. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86430. imageData[(x + width * y) * 4 + 3] = 255;
  86431. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86432. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86433. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86434. }
  86435. }
  86436. return imageData;
  86437. };
  86438. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86439. var image = pixel_data;
  86440. var width = header.width, height = header.height;
  86441. var i = 0, x, y;
  86442. var imageData = new Uint8Array(width * height * 4);
  86443. for (y = y_start; y !== y_end; y += y_step) {
  86444. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86445. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86446. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86447. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86448. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86449. }
  86450. }
  86451. return imageData;
  86452. };
  86453. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86454. var image = pixel_data;
  86455. var width = header.width, height = header.height;
  86456. var color, i = 0, x, y;
  86457. var imageData = new Uint8Array(width * height * 4);
  86458. for (y = y_start; y !== y_end; y += y_step) {
  86459. for (x = x_start; x !== x_end; x += x_step, i++) {
  86460. color = image[i];
  86461. imageData[(x + width * y) * 4 + 0] = color;
  86462. imageData[(x + width * y) * 4 + 1] = color;
  86463. imageData[(x + width * y) * 4 + 2] = color;
  86464. imageData[(x + width * y) * 4 + 3] = 255;
  86465. }
  86466. }
  86467. return imageData;
  86468. };
  86469. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86470. var image = pixel_data;
  86471. var width = header.width, height = header.height;
  86472. var i = 0, x, y;
  86473. var imageData = new Uint8Array(width * height * 4);
  86474. for (y = y_start; y !== y_end; y += y_step) {
  86475. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86476. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86477. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86478. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86479. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86480. }
  86481. }
  86482. return imageData;
  86483. };
  86484. //private static _TYPE_NO_DATA = 0;
  86485. TGATools._TYPE_INDEXED = 1;
  86486. TGATools._TYPE_RGB = 2;
  86487. TGATools._TYPE_GREY = 3;
  86488. TGATools._TYPE_RLE_INDEXED = 9;
  86489. TGATools._TYPE_RLE_RGB = 10;
  86490. TGATools._TYPE_RLE_GREY = 11;
  86491. TGATools._ORIGIN_MASK = 0x30;
  86492. TGATools._ORIGIN_SHIFT = 0x04;
  86493. TGATools._ORIGIN_BL = 0x00;
  86494. TGATools._ORIGIN_BR = 0x01;
  86495. TGATools._ORIGIN_UL = 0x02;
  86496. TGATools._ORIGIN_UR = 0x03;
  86497. return TGATools;
  86498. }());
  86499. BABYLON.TGATools = TGATools;
  86500. })(BABYLON || (BABYLON = {}));
  86501. //# sourceMappingURL=babylon.tga.js.map
  86502. var BABYLON;
  86503. (function (BABYLON) {
  86504. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86505. // All values and structures referenced from:
  86506. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86507. var DDS_MAGIC = 0x20534444;
  86508. var
  86509. //DDSD_CAPS = 0x1,
  86510. //DDSD_HEIGHT = 0x2,
  86511. //DDSD_WIDTH = 0x4,
  86512. //DDSD_PITCH = 0x8,
  86513. //DDSD_PIXELFORMAT = 0x1000,
  86514. DDSD_MIPMAPCOUNT = 0x20000;
  86515. //DDSD_LINEARSIZE = 0x80000,
  86516. //DDSD_DEPTH = 0x800000;
  86517. // var DDSCAPS_COMPLEX = 0x8,
  86518. // DDSCAPS_MIPMAP = 0x400000,
  86519. // DDSCAPS_TEXTURE = 0x1000;
  86520. var DDSCAPS2_CUBEMAP = 0x200;
  86521. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86522. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86523. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86524. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86525. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86526. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86527. // DDSCAPS2_VOLUME = 0x200000;
  86528. var
  86529. //DDPF_ALPHAPIXELS = 0x1,
  86530. //DDPF_ALPHA = 0x2,
  86531. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86532. //DDPF_YUV = 0x200,
  86533. DDPF_LUMINANCE = 0x20000;
  86534. function FourCCToInt32(value) {
  86535. return value.charCodeAt(0) +
  86536. (value.charCodeAt(1) << 8) +
  86537. (value.charCodeAt(2) << 16) +
  86538. (value.charCodeAt(3) << 24);
  86539. }
  86540. function Int32ToFourCC(value) {
  86541. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86542. }
  86543. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86544. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86545. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86546. var FOURCC_DX10 = FourCCToInt32("DX10");
  86547. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86548. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86549. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86550. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86551. var headerLengthInt = 31; // The header length in 32 bit ints
  86552. // Offsets into the header array
  86553. var off_magic = 0;
  86554. var off_size = 1;
  86555. var off_flags = 2;
  86556. var off_height = 3;
  86557. var off_width = 4;
  86558. var off_mipmapCount = 7;
  86559. var off_pfFlags = 20;
  86560. var off_pfFourCC = 21;
  86561. var off_RGBbpp = 22;
  86562. var off_RMask = 23;
  86563. var off_GMask = 24;
  86564. var off_BMask = 25;
  86565. var off_AMask = 26;
  86566. // var off_caps1 = 27;
  86567. var off_caps2 = 28;
  86568. // var off_caps3 = 29;
  86569. // var off_caps4 = 30;
  86570. var off_dxgiFormat = 32;
  86571. ;
  86572. var DDSTools = /** @class */ (function () {
  86573. function DDSTools() {
  86574. }
  86575. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86576. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86577. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86578. var mipmapCount = 1;
  86579. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86580. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86581. }
  86582. var fourCC = header[off_pfFourCC];
  86583. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86584. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86585. switch (fourCC) {
  86586. case FOURCC_D3DFMT_R16G16B16A16F:
  86587. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86588. break;
  86589. case FOURCC_D3DFMT_R32G32B32A32F:
  86590. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86591. break;
  86592. case FOURCC_DX10:
  86593. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86594. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86595. break;
  86596. }
  86597. }
  86598. return {
  86599. width: header[off_width],
  86600. height: header[off_height],
  86601. mipmapCount: mipmapCount,
  86602. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86603. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86604. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86605. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86606. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86607. dxgiFormat: dxgiFormat,
  86608. textureType: textureType
  86609. };
  86610. };
  86611. DDSTools._ToHalfFloat = function (value) {
  86612. if (!DDSTools._FloatView) {
  86613. DDSTools._FloatView = new Float32Array(1);
  86614. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86615. }
  86616. DDSTools._FloatView[0] = value;
  86617. var x = DDSTools._Int32View[0];
  86618. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86619. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86620. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86621. /* If zero, or denormal, or exponent underflows too much for a denormal
  86622. * half, return signed zero. */
  86623. if (e < 103) {
  86624. return bits;
  86625. }
  86626. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86627. if (e > 142) {
  86628. bits |= 0x7c00;
  86629. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86630. * not Inf, so make sure we set one mantissa bit too. */
  86631. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86632. return bits;
  86633. }
  86634. /* If exponent underflows but not too much, return a denormal */
  86635. if (e < 113) {
  86636. m |= 0x0800;
  86637. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86638. * to 1, which is OK. */
  86639. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86640. return bits;
  86641. }
  86642. bits |= ((e - 112) << 10) | (m >> 1);
  86643. bits += m & 1;
  86644. return bits;
  86645. };
  86646. DDSTools._FromHalfFloat = function (value) {
  86647. var s = (value & 0x8000) >> 15;
  86648. var e = (value & 0x7C00) >> 10;
  86649. var f = value & 0x03FF;
  86650. if (e === 0) {
  86651. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  86652. }
  86653. else if (e == 0x1F) {
  86654. return f ? NaN : ((s ? -1 : 1) * Infinity);
  86655. }
  86656. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  86657. };
  86658. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86659. var destArray = new Float32Array(dataLength);
  86660. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86661. var index = 0;
  86662. for (var y = 0; y < height; y++) {
  86663. for (var x = 0; x < width; x++) {
  86664. var srcPos = (x + y * width) * 4;
  86665. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  86666. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  86667. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  86668. if (DDSTools.StoreLODInAlphaChannel) {
  86669. destArray[index + 3] = lod;
  86670. }
  86671. else {
  86672. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  86673. }
  86674. index += 4;
  86675. }
  86676. }
  86677. return destArray;
  86678. };
  86679. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86680. if (DDSTools.StoreLODInAlphaChannel) {
  86681. var destArray = new Uint16Array(dataLength);
  86682. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86683. var index = 0;
  86684. for (var y = 0; y < height; y++) {
  86685. for (var x = 0; x < width; x++) {
  86686. var srcPos = (x + y * width) * 4;
  86687. destArray[index] = srcData[srcPos];
  86688. destArray[index + 1] = srcData[srcPos + 1];
  86689. destArray[index + 2] = srcData[srcPos + 2];
  86690. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  86691. index += 4;
  86692. }
  86693. }
  86694. return destArray;
  86695. }
  86696. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  86697. };
  86698. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86699. if (DDSTools.StoreLODInAlphaChannel) {
  86700. var destArray = new Float32Array(dataLength);
  86701. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86702. var index = 0;
  86703. for (var y = 0; y < height; y++) {
  86704. for (var x = 0; x < width; x++) {
  86705. var srcPos = (x + y * width) * 4;
  86706. destArray[index] = srcData[srcPos];
  86707. destArray[index + 1] = srcData[srcPos + 1];
  86708. destArray[index + 2] = srcData[srcPos + 2];
  86709. destArray[index + 3] = lod;
  86710. index += 4;
  86711. }
  86712. }
  86713. return destArray;
  86714. }
  86715. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  86716. };
  86717. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86718. var destArray = new Uint8Array(dataLength);
  86719. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86720. var index = 0;
  86721. for (var y = 0; y < height; y++) {
  86722. for (var x = 0; x < width; x++) {
  86723. var srcPos = (x + y * width) * 4;
  86724. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  86725. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  86726. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  86727. if (DDSTools.StoreLODInAlphaChannel) {
  86728. destArray[index + 3] = lod;
  86729. }
  86730. else {
  86731. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  86732. }
  86733. index += 4;
  86734. }
  86735. }
  86736. return destArray;
  86737. };
  86738. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86739. var destArray = new Uint8Array(dataLength);
  86740. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86741. var index = 0;
  86742. for (var y = 0; y < height; y++) {
  86743. for (var x = 0; x < width; x++) {
  86744. var srcPos = (x + y * width) * 4;
  86745. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  86746. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  86747. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  86748. if (DDSTools.StoreLODInAlphaChannel) {
  86749. destArray[index + 3] = lod;
  86750. }
  86751. else {
  86752. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  86753. }
  86754. index += 4;
  86755. }
  86756. }
  86757. return destArray;
  86758. };
  86759. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  86760. var byteArray = new Uint8Array(dataLength);
  86761. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86762. var index = 0;
  86763. for (var y = 0; y < height; y++) {
  86764. for (var x = 0; x < width; x++) {
  86765. var srcPos = (x + y * width) * 4;
  86766. byteArray[index] = srcData[srcPos + rOffset];
  86767. byteArray[index + 1] = srcData[srcPos + gOffset];
  86768. byteArray[index + 2] = srcData[srcPos + bOffset];
  86769. byteArray[index + 3] = srcData[srcPos + aOffset];
  86770. index += 4;
  86771. }
  86772. }
  86773. return byteArray;
  86774. };
  86775. DDSTools._ExtractLongWordOrder = function (value) {
  86776. if (value === 0 || value === 255 || value === -16777216) {
  86777. return 0;
  86778. }
  86779. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86780. };
  86781. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86782. var byteArray = new Uint8Array(dataLength);
  86783. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86784. var index = 0;
  86785. for (var y = 0; y < height; y++) {
  86786. for (var x = 0; x < width; x++) {
  86787. var srcPos = (x + y * width) * 3;
  86788. byteArray[index] = srcData[srcPos + rOffset];
  86789. byteArray[index + 1] = srcData[srcPos + gOffset];
  86790. byteArray[index + 2] = srcData[srcPos + bOffset];
  86791. index += 3;
  86792. }
  86793. }
  86794. return byteArray;
  86795. };
  86796. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86797. var byteArray = new Uint8Array(dataLength);
  86798. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86799. var index = 0;
  86800. for (var y = 0; y < height; y++) {
  86801. for (var x = 0; x < width; x++) {
  86802. var srcPos = (x + y * width);
  86803. byteArray[index] = srcData[srcPos];
  86804. index++;
  86805. }
  86806. }
  86807. return byteArray;
  86808. };
  86809. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86810. if (lodIndex === void 0) { lodIndex = -1; }
  86811. var sphericalPolynomialFaces = null;
  86812. if (info.sphericalPolynomial) {
  86813. sphericalPolynomialFaces = new Array();
  86814. }
  86815. var ext = engine.getCaps().s3tc;
  86816. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86817. var fourCC, width, height, dataLength = 0, dataOffset;
  86818. var byteArray, mipmapCount, mip;
  86819. var internalFormat = 0;
  86820. var format = 0;
  86821. var blockBytes = 1;
  86822. if (header[off_magic] !== DDS_MAGIC) {
  86823. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86824. return;
  86825. }
  86826. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86827. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86828. return;
  86829. }
  86830. if (info.isCompressed && !ext) {
  86831. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86832. return;
  86833. }
  86834. var bpp = header[off_RGBbpp];
  86835. dataOffset = header[off_size] + 4;
  86836. var computeFormats = false;
  86837. if (info.isFourCC) {
  86838. fourCC = header[off_pfFourCC];
  86839. switch (fourCC) {
  86840. case FOURCC_DXT1:
  86841. blockBytes = 8;
  86842. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86843. break;
  86844. case FOURCC_DXT3:
  86845. blockBytes = 16;
  86846. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86847. break;
  86848. case FOURCC_DXT5:
  86849. blockBytes = 16;
  86850. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86851. break;
  86852. case FOURCC_D3DFMT_R16G16B16A16F:
  86853. computeFormats = true;
  86854. break;
  86855. case FOURCC_D3DFMT_R32G32B32A32F:
  86856. computeFormats = true;
  86857. break;
  86858. case FOURCC_DX10:
  86859. // There is an additionnal header so dataOffset need to be changed
  86860. dataOffset += 5 * 4; // 5 uints
  86861. var supported = false;
  86862. switch (info.dxgiFormat) {
  86863. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86864. computeFormats = true;
  86865. supported = true;
  86866. break;
  86867. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86868. info.isRGB = true;
  86869. info.isFourCC = false;
  86870. bpp = 32;
  86871. supported = true;
  86872. break;
  86873. }
  86874. if (supported) {
  86875. break;
  86876. }
  86877. default:
  86878. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86879. return;
  86880. }
  86881. }
  86882. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86883. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86884. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86885. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86886. if (computeFormats) {
  86887. format = engine._getWebGLTextureType(info.textureType);
  86888. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86889. }
  86890. mipmapCount = 1;
  86891. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86892. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86893. }
  86894. for (var face = 0; face < faces; face++) {
  86895. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86896. width = header[off_width];
  86897. height = header[off_height];
  86898. for (mip = 0; mip < mipmapCount; ++mip) {
  86899. if (lodIndex === -1 || lodIndex === mip) {
  86900. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86901. var i = (lodIndex === -1) ? mip : 0;
  86902. if (!info.isCompressed && info.isFourCC) {
  86903. dataLength = width * height * 4;
  86904. var floatArray = null;
  86905. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86906. if (bpp === 128) {
  86907. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86908. if (sphericalPolynomialFaces && i == 0) {
  86909. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86910. }
  86911. }
  86912. else if (bpp === 64) {
  86913. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86914. if (sphericalPolynomialFaces && i == 0) {
  86915. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86916. }
  86917. }
  86918. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86919. format = engine._getWebGLTextureType(info.textureType);
  86920. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86921. }
  86922. else {
  86923. if (bpp === 128) {
  86924. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86925. if (sphericalPolynomialFaces && i == 0) {
  86926. sphericalPolynomialFaces.push(floatArray);
  86927. }
  86928. }
  86929. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86930. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86931. if (sphericalPolynomialFaces && i == 0) {
  86932. sphericalPolynomialFaces.push(floatArray);
  86933. }
  86934. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86935. format = engine._getWebGLTextureType(info.textureType);
  86936. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86937. }
  86938. else { // 64
  86939. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86940. if (sphericalPolynomialFaces && i == 0) {
  86941. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86942. }
  86943. }
  86944. }
  86945. if (floatArray) {
  86946. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86947. }
  86948. }
  86949. else if (info.isRGB) {
  86950. if (bpp === 24) {
  86951. dataLength = width * height * 3;
  86952. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86953. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86954. }
  86955. else { // 32
  86956. dataLength = width * height * 4;
  86957. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86958. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86959. }
  86960. }
  86961. else if (info.isLuminance) {
  86962. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86963. var unpaddedRowSize = width;
  86964. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86965. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86966. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86967. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86968. }
  86969. else {
  86970. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86971. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86972. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86973. }
  86974. }
  86975. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86976. width *= 0.5;
  86977. height *= 0.5;
  86978. width = Math.max(1.0, width);
  86979. height = Math.max(1.0, height);
  86980. }
  86981. if (currentFace !== undefined) {
  86982. // Loading a single face
  86983. break;
  86984. }
  86985. }
  86986. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86987. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86988. size: header[off_width],
  86989. right: sphericalPolynomialFaces[0],
  86990. left: sphericalPolynomialFaces[1],
  86991. up: sphericalPolynomialFaces[2],
  86992. down: sphericalPolynomialFaces[3],
  86993. front: sphericalPolynomialFaces[4],
  86994. back: sphericalPolynomialFaces[5],
  86995. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86996. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86997. gammaSpace: false,
  86998. });
  86999. }
  87000. else {
  87001. info.sphericalPolynomial = undefined;
  87002. }
  87003. };
  87004. DDSTools.StoreLODInAlphaChannel = false;
  87005. return DDSTools;
  87006. }());
  87007. BABYLON.DDSTools = DDSTools;
  87008. })(BABYLON || (BABYLON = {}));
  87009. //# sourceMappingURL=babylon.dds.js.map
  87010. var BABYLON;
  87011. (function (BABYLON) {
  87012. /**
  87013. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87014. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87015. */
  87016. var KhronosTextureContainer = /** @class */ (function () {
  87017. /**
  87018. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87019. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87020. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87021. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87022. */
  87023. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87024. this.arrayBuffer = arrayBuffer;
  87025. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87026. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87027. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87028. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87029. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87030. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87031. BABYLON.Tools.Error("texture missing KTX identifier");
  87032. return;
  87033. }
  87034. // load the reset of the header in native 32 bit int
  87035. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87036. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87037. var oppositeEndianess = header[0] === 0x01020304;
  87038. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87039. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87040. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87041. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87042. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87043. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87044. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87045. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87046. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87047. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87048. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87049. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87050. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87051. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87052. if (this.glType !== 0) {
  87053. BABYLON.Tools.Error("only compressed formats currently supported");
  87054. return;
  87055. }
  87056. else {
  87057. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87058. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87059. }
  87060. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87061. BABYLON.Tools.Error("only 2D textures currently supported");
  87062. return;
  87063. }
  87064. if (this.numberOfArrayElements !== 0) {
  87065. BABYLON.Tools.Error("texture arrays not currently supported");
  87066. return;
  87067. }
  87068. if (this.numberOfFaces !== facesExpected) {
  87069. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87070. return;
  87071. }
  87072. // we now have a completely validated file, so could use existence of loadType as success
  87073. // would need to make this more elaborate & adjust checks above to support more than one load type
  87074. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87075. }
  87076. // not as fast hardware based, but will probably never need to use
  87077. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87078. return ((val & 0xFF) << 24)
  87079. | ((val & 0xFF00) << 8)
  87080. | ((val >> 8) & 0xFF00)
  87081. | ((val >> 24) & 0xFF);
  87082. };
  87083. /**
  87084. * It is assumed that the texture has already been created & is currently bound
  87085. */
  87086. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87087. switch (this.loadType) {
  87088. case KhronosTextureContainer.COMPRESSED_2D:
  87089. this._upload2DCompressedLevels(gl, loadMipmaps);
  87090. break;
  87091. case KhronosTextureContainer.TEX_2D:
  87092. case KhronosTextureContainer.COMPRESSED_3D:
  87093. case KhronosTextureContainer.TEX_3D:
  87094. }
  87095. };
  87096. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87097. // initialize width & height for level 1
  87098. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87099. var width = this.pixelWidth;
  87100. var height = this.pixelHeight;
  87101. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87102. for (var level = 0; level < mipmapCount; level++) {
  87103. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87104. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87105. for (var face = 0; face < this.numberOfFaces; face++) {
  87106. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87107. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87108. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87109. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87110. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87111. }
  87112. width = Math.max(1.0, width * 0.5);
  87113. height = Math.max(1.0, height * 0.5);
  87114. }
  87115. };
  87116. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87117. // load types
  87118. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87119. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87120. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87121. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87122. return KhronosTextureContainer;
  87123. }());
  87124. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87125. })(BABYLON || (BABYLON = {}));
  87126. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87127. var BABYLON;
  87128. (function (BABYLON) {
  87129. var Debug;
  87130. (function (Debug) {
  87131. /**
  87132. * Class used to render a debug view of a given skeleton
  87133. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87134. */
  87135. var SkeletonViewer = /** @class */ (function () {
  87136. /**
  87137. * Creates a new SkeletonViewer
  87138. * @param skeleton defines the skeleton to render
  87139. * @param mesh defines the mesh attached to the skeleton
  87140. * @param scene defines the hosting scene
  87141. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87142. * @param renderingGroupId defines the rendering group id to use with the viewer
  87143. */
  87144. function SkeletonViewer(
  87145. /** defines the skeleton to render */
  87146. skeleton,
  87147. /** defines the mesh attached to the skeleton */
  87148. mesh, scene,
  87149. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87150. autoUpdateBonesMatrices,
  87151. /** defines the rendering group id to use with the viewer */
  87152. renderingGroupId) {
  87153. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87154. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87155. this.skeleton = skeleton;
  87156. this.mesh = mesh;
  87157. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87158. this.renderingGroupId = renderingGroupId;
  87159. /** Gets or sets the color used to render the skeleton */
  87160. this.color = BABYLON.Color3.White();
  87161. this._debugLines = new Array();
  87162. this._isEnabled = false;
  87163. this._scene = scene;
  87164. this.update();
  87165. this._renderFunction = this.update.bind(this);
  87166. }
  87167. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87168. get: function () {
  87169. return this._isEnabled;
  87170. },
  87171. /** Gets or sets a boolean indicating if the viewer is enabled */
  87172. set: function (value) {
  87173. if (this._isEnabled === value) {
  87174. return;
  87175. }
  87176. this._isEnabled = value;
  87177. if (value) {
  87178. this._scene.registerBeforeRender(this._renderFunction);
  87179. }
  87180. else {
  87181. this._scene.unregisterBeforeRender(this._renderFunction);
  87182. }
  87183. },
  87184. enumerable: true,
  87185. configurable: true
  87186. });
  87187. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87188. if (x === void 0) { x = 0; }
  87189. if (y === void 0) { y = 0; }
  87190. if (z === void 0) { z = 0; }
  87191. var tmat = BABYLON.Tmp.Matrix[0];
  87192. var parentBone = bone.getParent();
  87193. tmat.copyFrom(bone.getLocalMatrix());
  87194. if (x !== 0 || y !== 0 || z !== 0) {
  87195. var tmat2 = BABYLON.Tmp.Matrix[1];
  87196. BABYLON.Matrix.IdentityToRef(tmat2);
  87197. tmat2.m[12] = x;
  87198. tmat2.m[13] = y;
  87199. tmat2.m[14] = z;
  87200. tmat2.multiplyToRef(tmat, tmat);
  87201. }
  87202. if (parentBone) {
  87203. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87204. }
  87205. tmat.multiplyToRef(meshMat, tmat);
  87206. position.x = tmat.m[12];
  87207. position.y = tmat.m[13];
  87208. position.z = tmat.m[14];
  87209. };
  87210. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87211. var len = bones.length;
  87212. var meshPos = this.mesh.position;
  87213. for (var i = 0; i < len; i++) {
  87214. var bone = bones[i];
  87215. var points = this._debugLines[i];
  87216. if (!points) {
  87217. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87218. this._debugLines[i] = points;
  87219. }
  87220. this._getBonePosition(points[0], bone, meshMat);
  87221. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87222. points[0].subtractInPlace(meshPos);
  87223. points[1].subtractInPlace(meshPos);
  87224. }
  87225. };
  87226. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87227. var len = bones.length;
  87228. var boneNum = 0;
  87229. var meshPos = this.mesh.position;
  87230. for (var i = len - 1; i >= 0; i--) {
  87231. var childBone = bones[i];
  87232. var parentBone = childBone.getParent();
  87233. if (!parentBone) {
  87234. continue;
  87235. }
  87236. var points = this._debugLines[boneNum];
  87237. if (!points) {
  87238. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87239. this._debugLines[boneNum] = points;
  87240. }
  87241. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87242. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87243. points[0].subtractInPlace(meshPos);
  87244. points[1].subtractInPlace(meshPos);
  87245. boneNum++;
  87246. }
  87247. };
  87248. /** Update the viewer to sync with current skeleton state */
  87249. SkeletonViewer.prototype.update = function () {
  87250. if (this.autoUpdateBonesMatrices) {
  87251. this.skeleton.computeAbsoluteTransforms();
  87252. }
  87253. if (this.skeleton.bones[0].length === undefined) {
  87254. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87255. }
  87256. else {
  87257. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87258. }
  87259. if (!this._debugMesh) {
  87260. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87261. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87262. }
  87263. else {
  87264. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87265. }
  87266. this._debugMesh.position.copyFrom(this.mesh.position);
  87267. this._debugMesh.color = this.color;
  87268. };
  87269. /** Release associated resources */
  87270. SkeletonViewer.prototype.dispose = function () {
  87271. if (this._debugMesh) {
  87272. this.isEnabled = false;
  87273. this._debugMesh.dispose();
  87274. this._debugMesh = null;
  87275. }
  87276. };
  87277. return SkeletonViewer;
  87278. }());
  87279. Debug.SkeletonViewer = SkeletonViewer;
  87280. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87281. })(BABYLON || (BABYLON = {}));
  87282. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87283. /**
  87284. * Module Debug contains the (visual) components to debug a scene correctly
  87285. */
  87286. var BABYLON;
  87287. (function (BABYLON) {
  87288. var Debug;
  87289. (function (Debug) {
  87290. /**
  87291. * The Axes viewer will show 3 axes in a specific point in space
  87292. */
  87293. var AxesViewer = /** @class */ (function () {
  87294. /**
  87295. * Creates a new AxesViewer
  87296. * @param scene defines the hosting scene
  87297. * @param scaleLines defines a number used to scale line length (1 by default)
  87298. */
  87299. function AxesViewer(scene, scaleLines) {
  87300. if (scaleLines === void 0) { scaleLines = 1; }
  87301. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87302. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87303. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87304. /**
  87305. * Gets or sets a number used to scale line length
  87306. */
  87307. this.scaleLines = 1;
  87308. this.scaleLines = scaleLines;
  87309. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87310. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87311. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87312. this._xmesh.renderingGroupId = 2;
  87313. this._ymesh.renderingGroupId = 2;
  87314. this._zmesh.renderingGroupId = 2;
  87315. this._xmesh.material.checkReadyOnlyOnce = true;
  87316. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87317. this._ymesh.material.checkReadyOnlyOnce = true;
  87318. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87319. this._zmesh.material.checkReadyOnlyOnce = true;
  87320. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87321. this.scene = scene;
  87322. }
  87323. /**
  87324. * Force the viewer to update
  87325. * @param position defines the position of the viewer
  87326. * @param xaxis defines the x axis of the viewer
  87327. * @param yaxis defines the y axis of the viewer
  87328. * @param zaxis defines the z axis of the viewer
  87329. */
  87330. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87331. var scaleLines = this.scaleLines;
  87332. if (this._xmesh) {
  87333. this._xmesh.position.copyFrom(position);
  87334. }
  87335. if (this._ymesh) {
  87336. this._ymesh.position.copyFrom(position);
  87337. }
  87338. if (this._zmesh) {
  87339. this._zmesh.position.copyFrom(position);
  87340. }
  87341. var point2 = this._xline[1];
  87342. point2.x = xaxis.x * scaleLines;
  87343. point2.y = xaxis.y * scaleLines;
  87344. point2.z = xaxis.z * scaleLines;
  87345. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87346. point2 = this._yline[1];
  87347. point2.x = yaxis.x * scaleLines;
  87348. point2.y = yaxis.y * scaleLines;
  87349. point2.z = yaxis.z * scaleLines;
  87350. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87351. point2 = this._zline[1];
  87352. point2.x = zaxis.x * scaleLines;
  87353. point2.y = zaxis.y * scaleLines;
  87354. point2.z = zaxis.z * scaleLines;
  87355. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87356. };
  87357. /** Releases resources */
  87358. AxesViewer.prototype.dispose = function () {
  87359. if (this._xmesh) {
  87360. this._xmesh.dispose();
  87361. }
  87362. if (this._ymesh) {
  87363. this._ymesh.dispose();
  87364. }
  87365. if (this._zmesh) {
  87366. this._zmesh.dispose();
  87367. }
  87368. this._xmesh = null;
  87369. this._ymesh = null;
  87370. this._zmesh = null;
  87371. this.scene = null;
  87372. };
  87373. return AxesViewer;
  87374. }());
  87375. Debug.AxesViewer = AxesViewer;
  87376. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87377. })(BABYLON || (BABYLON = {}));
  87378. //# sourceMappingURL=babylon.axesViewer.js.map
  87379. var BABYLON;
  87380. (function (BABYLON) {
  87381. var Debug;
  87382. (function (Debug) {
  87383. /**
  87384. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87385. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87386. */
  87387. var BoneAxesViewer = /** @class */ (function (_super) {
  87388. __extends(BoneAxesViewer, _super);
  87389. /**
  87390. * Creates a new BoneAxesViewer
  87391. * @param scene defines the hosting scene
  87392. * @param bone defines the target bone
  87393. * @param mesh defines the target mesh
  87394. * @param scaleLines defines a scaling factor for line length (1 by default)
  87395. */
  87396. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87397. if (scaleLines === void 0) { scaleLines = 1; }
  87398. var _this = _super.call(this, scene, scaleLines) || this;
  87399. /** Gets current position */
  87400. _this.pos = BABYLON.Vector3.Zero();
  87401. /** Gets direction of X axis */
  87402. _this.xaxis = BABYLON.Vector3.Zero();
  87403. /** Gets direction of Y axis */
  87404. _this.yaxis = BABYLON.Vector3.Zero();
  87405. /** Gets direction of Z axis */
  87406. _this.zaxis = BABYLON.Vector3.Zero();
  87407. _this.mesh = mesh;
  87408. _this.bone = bone;
  87409. return _this;
  87410. }
  87411. /**
  87412. * Force the viewer to update
  87413. */
  87414. BoneAxesViewer.prototype.update = function () {
  87415. if (!this.mesh || !this.bone) {
  87416. return;
  87417. }
  87418. var bone = this.bone;
  87419. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87420. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87421. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87422. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87423. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87424. };
  87425. /** Releases resources */
  87426. BoneAxesViewer.prototype.dispose = function () {
  87427. if (this.mesh) {
  87428. this.mesh = null;
  87429. this.bone = null;
  87430. _super.prototype.dispose.call(this);
  87431. }
  87432. };
  87433. return BoneAxesViewer;
  87434. }(Debug.AxesViewer));
  87435. Debug.BoneAxesViewer = BoneAxesViewer;
  87436. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87437. })(BABYLON || (BABYLON = {}));
  87438. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87439. var BABYLON;
  87440. (function (BABYLON) {
  87441. var RayHelper = /** @class */ (function () {
  87442. function RayHelper(ray) {
  87443. this.ray = ray;
  87444. }
  87445. RayHelper.CreateAndShow = function (ray, scene, color) {
  87446. var helper = new RayHelper(ray);
  87447. helper.show(scene, color);
  87448. return helper;
  87449. };
  87450. RayHelper.prototype.show = function (scene, color) {
  87451. if (!this._renderFunction && this.ray) {
  87452. var ray = this.ray;
  87453. this._renderFunction = this._render.bind(this);
  87454. this._scene = scene;
  87455. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87456. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87457. if (this._renderFunction) {
  87458. this._scene.registerBeforeRender(this._renderFunction);
  87459. }
  87460. }
  87461. if (color && this._renderLine) {
  87462. this._renderLine.color.copyFrom(color);
  87463. }
  87464. };
  87465. RayHelper.prototype.hide = function () {
  87466. if (this._renderFunction && this._scene) {
  87467. this._scene.unregisterBeforeRender(this._renderFunction);
  87468. this._scene = null;
  87469. this._renderFunction = null;
  87470. if (this._renderLine) {
  87471. this._renderLine.dispose();
  87472. this._renderLine = null;
  87473. }
  87474. this._renderPoints = [];
  87475. }
  87476. };
  87477. RayHelper.prototype._render = function () {
  87478. var ray = this.ray;
  87479. if (!ray) {
  87480. return;
  87481. }
  87482. var point = this._renderPoints[1];
  87483. var len = Math.min(ray.length, 1000000);
  87484. point.copyFrom(ray.direction);
  87485. point.scaleInPlace(len);
  87486. point.addInPlace(ray.origin);
  87487. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87488. };
  87489. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87490. this._attachedToMesh = mesh;
  87491. var ray = this.ray;
  87492. if (!ray) {
  87493. return;
  87494. }
  87495. if (!ray.direction) {
  87496. ray.direction = BABYLON.Vector3.Zero();
  87497. }
  87498. if (!ray.origin) {
  87499. ray.origin = BABYLON.Vector3.Zero();
  87500. }
  87501. if (length) {
  87502. ray.length = length;
  87503. }
  87504. if (!meshSpaceOrigin) {
  87505. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87506. }
  87507. if (!meshSpaceDirection) {
  87508. // -1 so that this will work with Mesh.lookAt
  87509. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87510. }
  87511. if (!this._meshSpaceDirection) {
  87512. this._meshSpaceDirection = meshSpaceDirection.clone();
  87513. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87514. }
  87515. else {
  87516. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87517. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87518. }
  87519. if (!this._updateToMeshFunction) {
  87520. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87521. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87522. }
  87523. this._updateToMesh();
  87524. };
  87525. RayHelper.prototype.detachFromMesh = function () {
  87526. if (this._attachedToMesh) {
  87527. if (this._updateToMeshFunction) {
  87528. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87529. }
  87530. this._attachedToMesh = null;
  87531. this._updateToMeshFunction = null;
  87532. }
  87533. };
  87534. RayHelper.prototype._updateToMesh = function () {
  87535. var ray = this.ray;
  87536. if (!this._attachedToMesh || !ray) {
  87537. return;
  87538. }
  87539. if (this._attachedToMesh._isDisposed) {
  87540. this.detachFromMesh();
  87541. return;
  87542. }
  87543. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87544. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87545. };
  87546. RayHelper.prototype.dispose = function () {
  87547. this.hide();
  87548. this.detachFromMesh();
  87549. this.ray = null;
  87550. };
  87551. return RayHelper;
  87552. }());
  87553. BABYLON.RayHelper = RayHelper;
  87554. })(BABYLON || (BABYLON = {}));
  87555. //# sourceMappingURL=babylon.rayHelper.js.map
  87556. var BABYLON;
  87557. (function (BABYLON) {
  87558. // load the inspector using require, if not present in the global namespace.
  87559. var DebugLayer = /** @class */ (function () {
  87560. function DebugLayer(scene) {
  87561. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87562. this._scene = scene;
  87563. // load inspector using require, if it doesn't exist on the global namespace.
  87564. }
  87565. /** Creates the inspector window. */
  87566. DebugLayer.prototype._createInspector = function (config) {
  87567. if (config === void 0) { config = {}; }
  87568. var popup = config.popup || false;
  87569. var initialTab = config.initialTab || 0;
  87570. var parentElement = config.parentElement || null;
  87571. if (!this._inspector) {
  87572. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87573. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87574. } // else nothing to do,; instance is already existing
  87575. };
  87576. DebugLayer.prototype.isVisible = function () {
  87577. if (!this._inspector) {
  87578. return false;
  87579. }
  87580. return true;
  87581. };
  87582. DebugLayer.prototype.hide = function () {
  87583. if (this._inspector) {
  87584. try {
  87585. this._inspector.dispose();
  87586. }
  87587. catch (e) {
  87588. // If the inspector has been removed directly from the inspector tool
  87589. }
  87590. this.onPropertyChangedObservable.clear();
  87591. this._inspector = null;
  87592. }
  87593. };
  87594. /**
  87595. *
  87596. * Launch the debugLayer.
  87597. *
  87598. * initialTab:
  87599. * | Value | Tab Name |
  87600. * | --- | --- |
  87601. * | 0 | Scene |
  87602. * | 1 | Console |
  87603. * | 2 | Stats |
  87604. * | 3 | Textures |
  87605. * | 4 | Mesh |
  87606. * | 5 | Light |
  87607. * | 6 | Material |
  87608. * | 7 | GLTF |
  87609. * | 8 | GUI |
  87610. * | 9 | Physics |
  87611. * | 10 | Camera |
  87612. * | 11 | Audio |
  87613. *
  87614. */
  87615. DebugLayer.prototype.show = function (config) {
  87616. if (config === void 0) { config = {}; }
  87617. if (typeof this.BJSINSPECTOR == 'undefined') {
  87618. // Load inspector and add it to the DOM
  87619. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87620. }
  87621. else {
  87622. // Otherwise creates the inspector
  87623. this._createInspector(config);
  87624. this.onPropertyChangedObservable = new BABYLON.Observable();
  87625. }
  87626. };
  87627. /**
  87628. * Gets the active tab
  87629. * @return the index of the active tab or -1 if the inspector is hidden
  87630. */
  87631. DebugLayer.prototype.getActiveTab = function () {
  87632. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87633. };
  87634. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87635. return DebugLayer;
  87636. }());
  87637. BABYLON.DebugLayer = DebugLayer;
  87638. })(BABYLON || (BABYLON = {}));
  87639. //# sourceMappingURL=babylon.debugLayer.js.map
  87640. var BABYLON;
  87641. (function (BABYLON) {
  87642. var Debug;
  87643. (function (Debug) {
  87644. /**
  87645. * Used to show the physics impostor around the specific mesh
  87646. */
  87647. var PhysicsViewer = /** @class */ (function () {
  87648. /**
  87649. * Creates a new PhysicsViewer
  87650. * @param scene defines the hosting scene
  87651. */
  87652. function PhysicsViewer(scene) {
  87653. /** @hidden */
  87654. this._impostors = [];
  87655. /** @hidden */
  87656. this._meshes = [];
  87657. /** @hidden */
  87658. this._numMeshes = 0;
  87659. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87660. var physicEngine = this._scene.getPhysicsEngine();
  87661. if (physicEngine) {
  87662. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  87663. }
  87664. }
  87665. /** @hidden */
  87666. PhysicsViewer.prototype._updateDebugMeshes = function () {
  87667. var plugin = this._physicsEnginePlugin;
  87668. for (var i = 0; i < this._numMeshes; i++) {
  87669. var impostor = this._impostors[i];
  87670. if (!impostor) {
  87671. continue;
  87672. }
  87673. if (impostor.isDisposed) {
  87674. this.hideImpostor(this._impostors[i--]);
  87675. }
  87676. else {
  87677. var mesh = this._meshes[i];
  87678. if (mesh && plugin) {
  87679. plugin.syncMeshWithImpostor(mesh, impostor);
  87680. }
  87681. }
  87682. }
  87683. };
  87684. /**
  87685. * Renders a specified physic impostor
  87686. * @param impostor defines the impostor to render
  87687. */
  87688. PhysicsViewer.prototype.showImpostor = function (impostor) {
  87689. if (!this._scene) {
  87690. return;
  87691. }
  87692. for (var i = 0; i < this._numMeshes; i++) {
  87693. if (this._impostors[i] == impostor) {
  87694. return;
  87695. }
  87696. }
  87697. var debugMesh = this._getDebugMesh(impostor, this._scene);
  87698. if (debugMesh) {
  87699. this._impostors[this._numMeshes] = impostor;
  87700. this._meshes[this._numMeshes] = debugMesh;
  87701. if (this._numMeshes === 0) {
  87702. this._renderFunction = this._updateDebugMeshes.bind(this);
  87703. this._scene.registerBeforeRender(this._renderFunction);
  87704. }
  87705. this._numMeshes++;
  87706. }
  87707. };
  87708. /**
  87709. * Hides a specified physic impostor
  87710. * @param impostor defines the impostor to hide
  87711. */
  87712. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  87713. if (!impostor || !this._scene) {
  87714. return;
  87715. }
  87716. var removed = false;
  87717. for (var i = 0; i < this._numMeshes; i++) {
  87718. if (this._impostors[i] == impostor) {
  87719. var mesh = this._meshes[i];
  87720. if (!mesh) {
  87721. continue;
  87722. }
  87723. this._scene.removeMesh(mesh);
  87724. mesh.dispose();
  87725. this._numMeshes--;
  87726. if (this._numMeshes > 0) {
  87727. this._meshes[i] = this._meshes[this._numMeshes];
  87728. this._impostors[i] = this._impostors[this._numMeshes];
  87729. this._meshes[this._numMeshes] = null;
  87730. this._impostors[this._numMeshes] = null;
  87731. }
  87732. else {
  87733. this._meshes[0] = null;
  87734. this._impostors[0] = null;
  87735. }
  87736. removed = true;
  87737. break;
  87738. }
  87739. }
  87740. if (removed && this._numMeshes === 0) {
  87741. this._scene.unregisterBeforeRender(this._renderFunction);
  87742. }
  87743. };
  87744. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  87745. if (!this._debugMaterial) {
  87746. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  87747. this._debugMaterial.wireframe = true;
  87748. }
  87749. return this._debugMaterial;
  87750. };
  87751. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  87752. if (!this._debugBoxMesh) {
  87753. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  87754. this._debugBoxMesh.renderingGroupId = 1;
  87755. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87756. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  87757. scene.removeMesh(this._debugBoxMesh);
  87758. }
  87759. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  87760. };
  87761. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87762. if (!this._debugSphereMesh) {
  87763. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87764. this._debugSphereMesh.renderingGroupId = 1;
  87765. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87766. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87767. scene.removeMesh(this._debugSphereMesh);
  87768. }
  87769. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87770. };
  87771. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87772. var mesh = null;
  87773. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87774. mesh = this._getDebugBoxMesh(scene);
  87775. impostor.getBoxSizeToRef(mesh.scaling);
  87776. }
  87777. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87778. mesh = this._getDebugSphereMesh(scene);
  87779. var radius = impostor.getRadius();
  87780. mesh.scaling.x = radius * 2;
  87781. mesh.scaling.y = radius * 2;
  87782. mesh.scaling.z = radius * 2;
  87783. }
  87784. return mesh;
  87785. };
  87786. /** Releases all resources */
  87787. PhysicsViewer.prototype.dispose = function () {
  87788. for (var i = 0; i < this._numMeshes; i++) {
  87789. this.hideImpostor(this._impostors[i]);
  87790. }
  87791. if (this._debugBoxMesh) {
  87792. this._debugBoxMesh.dispose();
  87793. }
  87794. if (this._debugSphereMesh) {
  87795. this._debugSphereMesh.dispose();
  87796. }
  87797. if (this._debugMaterial) {
  87798. this._debugMaterial.dispose();
  87799. }
  87800. this._impostors.length = 0;
  87801. this._scene = null;
  87802. this._physicsEnginePlugin = null;
  87803. };
  87804. return PhysicsViewer;
  87805. }());
  87806. Debug.PhysicsViewer = PhysicsViewer;
  87807. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87808. })(BABYLON || (BABYLON = {}));
  87809. //# sourceMappingURL=babylon.physicsViewer.js.map
  87810. var BABYLON;
  87811. (function (BABYLON) {
  87812. var BoundingBoxRenderer = /** @class */ (function () {
  87813. function BoundingBoxRenderer(scene) {
  87814. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87815. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87816. this.showBackLines = true;
  87817. this.renderList = new BABYLON.SmartArray(32);
  87818. this._vertexBuffers = {};
  87819. this._scene = scene;
  87820. }
  87821. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87822. if (this._colorShader) {
  87823. return;
  87824. }
  87825. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87826. attributes: [BABYLON.VertexBuffer.PositionKind],
  87827. uniforms: ["world", "viewProjection", "color"]
  87828. });
  87829. var engine = this._scene.getEngine();
  87830. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87831. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87832. this._createIndexBuffer();
  87833. };
  87834. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87835. var engine = this._scene.getEngine();
  87836. 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]);
  87837. };
  87838. BoundingBoxRenderer.prototype._rebuild = function () {
  87839. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87840. if (vb) {
  87841. vb._rebuild();
  87842. }
  87843. this._createIndexBuffer();
  87844. };
  87845. BoundingBoxRenderer.prototype.reset = function () {
  87846. this.renderList.reset();
  87847. };
  87848. BoundingBoxRenderer.prototype.render = function () {
  87849. if (this.renderList.length === 0) {
  87850. return;
  87851. }
  87852. this._prepareRessources();
  87853. if (!this._colorShader.isReady()) {
  87854. return;
  87855. }
  87856. var engine = this._scene.getEngine();
  87857. engine.setDepthWrite(false);
  87858. this._colorShader._preBind();
  87859. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87860. var boundingBox = this.renderList.data[boundingBoxIndex];
  87861. var min = boundingBox.minimum;
  87862. var max = boundingBox.maximum;
  87863. var diff = max.subtract(min);
  87864. var median = min.add(diff.scale(0.5));
  87865. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87866. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87867. .multiply(boundingBox.getWorldMatrix());
  87868. // VBOs
  87869. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87870. if (this.showBackLines) {
  87871. // Back
  87872. engine.setDepthFunctionToGreaterOrEqual();
  87873. this._scene.resetCachedMaterial();
  87874. this._colorShader.setColor4("color", this.backColor.toColor4());
  87875. this._colorShader.bind(worldMatrix);
  87876. // Draw order
  87877. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87878. }
  87879. // Front
  87880. engine.setDepthFunctionToLess();
  87881. this._scene.resetCachedMaterial();
  87882. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87883. this._colorShader.bind(worldMatrix);
  87884. // Draw order
  87885. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87886. }
  87887. this._colorShader.unbind();
  87888. engine.setDepthFunctionToLessOrEqual();
  87889. engine.setDepthWrite(true);
  87890. };
  87891. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87892. this._prepareRessources();
  87893. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87894. return;
  87895. }
  87896. var engine = this._scene.getEngine();
  87897. engine.setDepthWrite(false);
  87898. engine.setColorWrite(false);
  87899. this._colorShader._preBind();
  87900. var boundingBox = mesh._boundingInfo.boundingBox;
  87901. var min = boundingBox.minimum;
  87902. var max = boundingBox.maximum;
  87903. var diff = max.subtract(min);
  87904. var median = min.add(diff.scale(0.5));
  87905. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87906. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87907. .multiply(boundingBox.getWorldMatrix());
  87908. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87909. engine.setDepthFunctionToLess();
  87910. this._scene.resetCachedMaterial();
  87911. this._colorShader.bind(worldMatrix);
  87912. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87913. this._colorShader.unbind();
  87914. engine.setDepthFunctionToLessOrEqual();
  87915. engine.setDepthWrite(true);
  87916. engine.setColorWrite(true);
  87917. };
  87918. BoundingBoxRenderer.prototype.dispose = function () {
  87919. if (!this._colorShader) {
  87920. return;
  87921. }
  87922. this.renderList.dispose();
  87923. this._colorShader.dispose();
  87924. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87925. if (buffer) {
  87926. buffer.dispose();
  87927. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87928. }
  87929. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87930. };
  87931. return BoundingBoxRenderer;
  87932. }());
  87933. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87934. })(BABYLON || (BABYLON = {}));
  87935. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87936. var BABYLON;
  87937. (function (BABYLON) {
  87938. /**
  87939. * Renders a layer on top of an existing scene
  87940. */
  87941. var UtilityLayerRenderer = /** @class */ (function () {
  87942. /**
  87943. * Instantiates a UtilityLayerRenderer
  87944. * @param originalScene the original scene that will be rendered on top of
  87945. */
  87946. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87947. var _this = this;
  87948. this.originalScene = originalScene;
  87949. this._pointerCaptures = {};
  87950. this._lastPointerEvents = {};
  87951. /**
  87952. * If the utility layer should automatically be rendered on top of existing scene
  87953. */
  87954. this.shouldRender = true;
  87955. /**
  87956. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87957. */
  87958. this.onlyCheckPointerDownEvents = true;
  87959. /**
  87960. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87961. */
  87962. this.processAllEvents = false;
  87963. /**
  87964. * Observable raised when the pointer move from the utility layer scene to the main scene
  87965. */
  87966. this.onPointerOutObservable = new BABYLON.Observable();
  87967. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87968. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87969. originalScene.getEngine().scenes.pop();
  87970. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87971. this.utilityLayerScene.detachControl();
  87972. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87973. if (!_this.processAllEvents) {
  87974. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87975. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87976. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87977. return;
  87978. }
  87979. }
  87980. var pointerEvent = (prePointerInfo.event);
  87981. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  87982. return;
  87983. }
  87984. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87985. if (!prePointerInfo.ray && utilityScenePick) {
  87986. prePointerInfo.ray = utilityScenePick.ray;
  87987. }
  87988. // always fire the prepointer oversvable
  87989. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87990. // allow every non pointer down event to flow to the utility layer
  87991. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87992. if (!prePointerInfo.skipOnPointerObservable) {
  87993. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87994. }
  87995. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87996. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87997. }
  87998. return;
  87999. }
  88000. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88001. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88002. if (utilityScenePick && utilityScenePick.hit) {
  88003. if (!prePointerInfo.skipOnPointerObservable) {
  88004. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88005. }
  88006. prePointerInfo.skipOnPointerObservable = true;
  88007. }
  88008. }
  88009. else {
  88010. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88011. var pointerEvent_1 = (prePointerInfo.event);
  88012. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88013. if (originalScenePick && utilityScenePick) {
  88014. // No pick in utility scene
  88015. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88016. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88017. // We touched an utility mesh present in the main scene
  88018. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88019. prePointerInfo.skipOnPointerObservable = true;
  88020. }
  88021. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88022. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88023. }
  88024. }
  88025. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88026. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88027. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88028. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88029. }
  88030. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88031. // We have a pick in both scenes but main is closer than utility
  88032. // We touched an utility mesh present in the main scene
  88033. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88034. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88035. prePointerInfo.skipOnPointerObservable = true;
  88036. }
  88037. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88038. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88039. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88040. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88041. }
  88042. }
  88043. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88044. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88045. }
  88046. }
  88047. }
  88048. });
  88049. // Render directly on top of existing scene without clearing
  88050. this.utilityLayerScene.autoClear = false;
  88051. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88052. if (_this.shouldRender) {
  88053. _this.render();
  88054. }
  88055. });
  88056. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88057. _this.dispose();
  88058. });
  88059. this._updateCamera();
  88060. }
  88061. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88062. if (!prePointerInfo.skipOnPointerObservable) {
  88063. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88064. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88065. }
  88066. };
  88067. /**
  88068. * Renders the utility layers scene on top of the original scene
  88069. */
  88070. UtilityLayerRenderer.prototype.render = function () {
  88071. this._updateCamera();
  88072. this.utilityLayerScene.render(false);
  88073. };
  88074. /**
  88075. * Disposes of the renderer
  88076. */
  88077. UtilityLayerRenderer.prototype.dispose = function () {
  88078. this.onPointerOutObservable.clear();
  88079. if (this._afterRenderObserver) {
  88080. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88081. }
  88082. if (this._sceneDisposeObserver) {
  88083. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88084. }
  88085. if (this._originalPointerObserver) {
  88086. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88087. }
  88088. this.utilityLayerScene.dispose();
  88089. };
  88090. UtilityLayerRenderer.prototype._updateCamera = function () {
  88091. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88092. };
  88093. return UtilityLayerRenderer;
  88094. }());
  88095. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88096. })(BABYLON || (BABYLON = {}));
  88097. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88098. //# sourceMappingURL=babylon.behavior.js.map
  88099. var BABYLON;
  88100. (function (BABYLON) {
  88101. /**
  88102. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88103. */
  88104. var PointerDragBehavior = /** @class */ (function () {
  88105. /**
  88106. * Creates a pointer drag behavior that can be attached to a mesh
  88107. * @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)
  88108. */
  88109. function PointerDragBehavior(options) {
  88110. this.options = options;
  88111. /**
  88112. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88113. */
  88114. this.currentDraggingPointerID = -1;
  88115. /**
  88116. * If the behavior is currently in a dragging state
  88117. */
  88118. this.dragging = false;
  88119. /**
  88120. * 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)
  88121. */
  88122. this.dragDeltaRatio = 0.2;
  88123. /**
  88124. * If the drag plane orientation should be updated during the dragging (Default: true)
  88125. */
  88126. this.updateDragPlane = true;
  88127. // Debug mode will display drag planes to help visualize behavior
  88128. this._debugMode = false;
  88129. this._moving = false;
  88130. /**
  88131. * Fires each time the attached mesh is dragged with the pointer
  88132. * * delta between last drag position and current drag position in world space
  88133. * * dragDistance along the drag axis
  88134. * * dragPlaneNormal normal of the current drag plane used during the drag
  88135. * * dragPlanePoint in world space where the drag intersects the drag plane
  88136. */
  88137. this.onDragObservable = new BABYLON.Observable();
  88138. /**
  88139. * Fires each time a drag begins (eg. mouse down on mesh)
  88140. */
  88141. this.onDragStartObservable = new BABYLON.Observable();
  88142. /**
  88143. * Fires each time a drag ends (eg. mouse release after drag)
  88144. */
  88145. this.onDragEndObservable = new BABYLON.Observable();
  88146. /**
  88147. * If the attached mesh should be moved when dragged
  88148. */
  88149. this.moveAttached = true;
  88150. /**
  88151. * If the drag behavior will react to drag events (Default: true)
  88152. */
  88153. this.enabled = true;
  88154. /**
  88155. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88156. */
  88157. this.useObjectOrienationForDragging = true;
  88158. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88159. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88160. // Variables to avoid instantiation in the below method
  88161. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88162. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88163. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88164. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88165. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88166. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88167. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88168. var optionCount = 0;
  88169. if (options === undefined) {
  88170. options = {};
  88171. }
  88172. if (options.dragAxis) {
  88173. optionCount++;
  88174. }
  88175. if (options.dragPlaneNormal) {
  88176. optionCount++;
  88177. }
  88178. if (optionCount > 1) {
  88179. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88180. }
  88181. }
  88182. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88183. /**
  88184. * The name of the behavior
  88185. */
  88186. get: function () {
  88187. return "PointerDrag";
  88188. },
  88189. enumerable: true,
  88190. configurable: true
  88191. });
  88192. /**
  88193. * Initializes the behavior
  88194. */
  88195. PointerDragBehavior.prototype.init = function () { };
  88196. /**
  88197. * Attaches the drag behavior the passed in mesh
  88198. * @param ownerNode The mesh that will be dragged around once attached
  88199. */
  88200. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88201. var _this = this;
  88202. this._scene = ownerNode.getScene();
  88203. this._attachedNode = ownerNode;
  88204. // Initialize drag plane to not interfere with existing scene
  88205. if (!PointerDragBehavior._planeScene) {
  88206. if (this._debugMode) {
  88207. PointerDragBehavior._planeScene = this._scene;
  88208. }
  88209. else {
  88210. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88211. this._scene.getEngine().scenes.pop();
  88212. }
  88213. }
  88214. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88215. // State of the drag
  88216. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88217. var delta = new BABYLON.Vector3(0, 0, 0);
  88218. var dragLength = 0;
  88219. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88220. var pickPredicate = function (m) {
  88221. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88222. };
  88223. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88224. if (!_this.enabled) {
  88225. return;
  88226. }
  88227. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88228. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88229. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88230. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88231. if (pickedPoint) {
  88232. _this.dragging = true;
  88233. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88234. _this.lastDragPosition.copyFrom(pickedPoint);
  88235. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88236. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88237. }
  88238. }
  88239. }
  88240. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88241. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88242. _this.releaseDrag();
  88243. }
  88244. }
  88245. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88246. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88247. _this._moving = true;
  88248. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88249. if (pickedPoint) {
  88250. if (_this.updateDragPlane) {
  88251. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88252. }
  88253. // depending on the drag mode option drag accordingly
  88254. if (_this.options.dragAxis) {
  88255. // Convert local drag axis to world
  88256. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88257. // Project delta drag from the drag plane onto the drag axis
  88258. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88259. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88260. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88261. }
  88262. else {
  88263. dragLength = delta.length();
  88264. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88265. }
  88266. targetPosition.addInPlace(delta);
  88267. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88268. _this.lastDragPosition.copyFrom(pickedPoint);
  88269. }
  88270. }
  88271. }
  88272. });
  88273. this._scene.onBeforeRenderObservable.add(function () {
  88274. if (_this._moving && _this.moveAttached) {
  88275. // Slowly move mesh to avoid jitter
  88276. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88277. _this._tmpVector.scaleInPlace(0.2);
  88278. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88279. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88280. }
  88281. });
  88282. };
  88283. PointerDragBehavior.prototype.releaseDrag = function () {
  88284. this.dragging = false;
  88285. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88286. this.currentDraggingPointerID = -1;
  88287. this._moving = false;
  88288. };
  88289. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88290. var _this = this;
  88291. if (!ray) {
  88292. return null;
  88293. }
  88294. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88295. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88296. return pickResult.pickedPoint;
  88297. }
  88298. else {
  88299. return null;
  88300. }
  88301. };
  88302. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88303. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88304. this._pointA.copyFrom(dragPlanePosition);
  88305. if (this.options.dragAxis) {
  88306. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88307. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88308. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88309. ray.origin.subtractToRef(this._pointA, this._pointC);
  88310. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88311. // Get perpendicular line from direction to camera and drag axis
  88312. this._pointB.subtractToRef(this._pointA, this._lineA);
  88313. this._pointC.subtractToRef(this._pointA, this._lineB);
  88314. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88315. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88316. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88317. this._lookAt.normalize();
  88318. this._dragPlane.position.copyFrom(this._pointA);
  88319. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88320. this._dragPlane.lookAt(this._lookAt);
  88321. }
  88322. else if (this.options.dragPlaneNormal) {
  88323. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88324. this._dragPlane.position.copyFrom(this._pointA);
  88325. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88326. this._dragPlane.lookAt(this._lookAt);
  88327. }
  88328. else {
  88329. this._dragPlane.position.copyFrom(this._pointA);
  88330. this._dragPlane.lookAt(ray.origin);
  88331. }
  88332. this._dragPlane.computeWorldMatrix(true);
  88333. };
  88334. /**
  88335. * Detaches the behavior from the mesh
  88336. */
  88337. PointerDragBehavior.prototype.detach = function () {
  88338. if (this._pointerObserver) {
  88339. this._scene.onPointerObservable.remove(this._pointerObserver);
  88340. }
  88341. };
  88342. return PointerDragBehavior;
  88343. }());
  88344. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88345. })(BABYLON || (BABYLON = {}));
  88346. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88347. var BABYLON;
  88348. (function (BABYLON) {
  88349. /**
  88350. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88351. */
  88352. var MultiPointerScaleBehavior = /** @class */ (function () {
  88353. function MultiPointerScaleBehavior() {
  88354. this._startDistance = 0;
  88355. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88356. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88357. this._sceneRenderObserver = null;
  88358. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88359. this._dragBehaviorA.moveAttached = false;
  88360. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88361. this._dragBehaviorB.moveAttached = false;
  88362. }
  88363. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88364. /**
  88365. * The name of the behavior
  88366. */
  88367. get: function () {
  88368. return "MultiPointerScale";
  88369. },
  88370. enumerable: true,
  88371. configurable: true
  88372. });
  88373. /**
  88374. * Initializes the behavior
  88375. */
  88376. MultiPointerScaleBehavior.prototype.init = function () { };
  88377. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88378. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88379. };
  88380. /**
  88381. * Attaches the scale behavior the passed in mesh
  88382. * @param ownerNode The mesh that will be scaled around once attached
  88383. */
  88384. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88385. var _this = this;
  88386. this._ownerNode = ownerNode;
  88387. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88388. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88389. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88390. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88391. _this._dragBehaviorA.releaseDrag();
  88392. }
  88393. else {
  88394. _this._initialScale.copyFrom(ownerNode.scaling);
  88395. _this._startDistance = _this._getCurrentDistance();
  88396. }
  88397. }
  88398. });
  88399. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88400. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88401. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88402. _this._dragBehaviorB.releaseDrag();
  88403. }
  88404. else {
  88405. _this._initialScale.copyFrom(ownerNode.scaling);
  88406. _this._startDistance = _this._getCurrentDistance();
  88407. }
  88408. }
  88409. });
  88410. // Once both drag behaviors are active scale based on the distance between the two pointers
  88411. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88412. behavior.onDragObservable.add(function () {
  88413. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88414. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88415. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88416. }
  88417. });
  88418. });
  88419. ownerNode.addBehavior(this._dragBehaviorA);
  88420. ownerNode.addBehavior(this._dragBehaviorB);
  88421. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88422. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88423. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88424. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88425. if (change.length() > 0.01) {
  88426. ownerNode.scaling.addInPlace(change);
  88427. }
  88428. }
  88429. });
  88430. };
  88431. /**
  88432. * Detaches the behavior from the mesh
  88433. */
  88434. MultiPointerScaleBehavior.prototype.detach = function () {
  88435. var _this = this;
  88436. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88437. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88438. behavior.onDragStartObservable.clear();
  88439. behavior.onDragObservable.clear();
  88440. _this._ownerNode.removeBehavior(behavior);
  88441. });
  88442. };
  88443. return MultiPointerScaleBehavior;
  88444. }());
  88445. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88446. })(BABYLON || (BABYLON = {}));
  88447. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88448. var BABYLON;
  88449. (function (BABYLON) {
  88450. /**
  88451. * 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
  88452. */
  88453. var SixDofDragBehavior = /** @class */ (function () {
  88454. function SixDofDragBehavior() {
  88455. this._sceneRenderObserver = null;
  88456. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88457. this._moving = false;
  88458. this._startingOrientation = new BABYLON.Quaternion();
  88459. /**
  88460. * 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: 5)
  88461. */
  88462. this.zDragFactor = 5;
  88463. /**
  88464. * If the behavior is currently in a dragging state
  88465. */
  88466. this.dragging = false;
  88467. /**
  88468. * 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)
  88469. */
  88470. this.dragDeltaRatio = 0.2;
  88471. /**
  88472. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88473. */
  88474. this.currentDraggingPointerID = -1;
  88475. }
  88476. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88477. /**
  88478. * The name of the behavior
  88479. */
  88480. get: function () {
  88481. return "SixDofDrag";
  88482. },
  88483. enumerable: true,
  88484. configurable: true
  88485. });
  88486. /**
  88487. * Initializes the behavior
  88488. */
  88489. SixDofDragBehavior.prototype.init = function () { };
  88490. /**
  88491. * Attaches the scale behavior the passed in mesh
  88492. * @param ownerNode The mesh that will be scaled around once attached
  88493. */
  88494. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88495. var _this = this;
  88496. this._ownerNode = ownerNode;
  88497. this._scene = this._ownerNode.getScene();
  88498. if (!SixDofDragBehavior._virtualScene) {
  88499. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88500. this._scene.getEngine().scenes.pop();
  88501. }
  88502. var pickedMesh = null;
  88503. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88504. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88505. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88506. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88507. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88508. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88509. var pickPredicate = function (m) {
  88510. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88511. };
  88512. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88513. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88514. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88515. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88516. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88517. // Set position and orientation of the controller
  88518. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88519. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88520. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88521. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88522. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88523. if (!pickedMesh.rotationQuaternion) {
  88524. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  88525. }
  88526. var oldParent = pickedMesh.parent;
  88527. pickedMesh.setParent(null);
  88528. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88529. pickedMesh.setParent(oldParent);
  88530. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88531. // Update state
  88532. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88533. _this.dragging = true;
  88534. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88535. }
  88536. }
  88537. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88538. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88539. _this.dragging = false;
  88540. _this._moving = false;
  88541. _this.currentDraggingPointerID = -1;
  88542. pickedMesh = null;
  88543. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88544. }
  88545. }
  88546. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88547. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88548. // Calculate controller drag distance in controller space
  88549. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88550. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88551. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88552. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88553. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88554. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88555. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88556. if (_this._virtualDragMesh.position.z < 0) {
  88557. _this._virtualDragMesh.position.z = 0;
  88558. }
  88559. // Update the controller position
  88560. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88561. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88562. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88563. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88564. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88565. if (pickedMesh.parent) {
  88566. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88567. }
  88568. if (!_this._moving) {
  88569. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  88570. }
  88571. _this._moving = true;
  88572. }
  88573. }
  88574. });
  88575. var tmpQuaternion = new BABYLON.Quaternion();
  88576. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88577. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88578. if (_this.dragging && _this._moving && pickedMesh) {
  88579. // Slowly move mesh to avoid jitter
  88580. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88581. // Get change in rotation
  88582. tmpQuaternion.copyFrom(_this._startingOrientation);
  88583. tmpQuaternion.x = -tmpQuaternion.x;
  88584. tmpQuaternion.y = -tmpQuaternion.y;
  88585. tmpQuaternion.z = -tmpQuaternion.z;
  88586. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  88587. // Convert change in rotation to only y axis rotation
  88588. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  88589. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  88590. // Slowly move mesh to avoid jitter
  88591. var oldParent = pickedMesh.parent;
  88592. pickedMesh.setParent(null);
  88593. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  88594. pickedMesh.setParent(oldParent);
  88595. }
  88596. });
  88597. };
  88598. /**
  88599. * Detaches the behavior from the mesh
  88600. */
  88601. SixDofDragBehavior.prototype.detach = function () {
  88602. this._scene.onPointerObservable.remove(this._pointerObserver);
  88603. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88604. this._virtualOriginMesh.dispose();
  88605. this._virtualDragMesh.dispose();
  88606. };
  88607. return SixDofDragBehavior;
  88608. }());
  88609. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88610. })(BABYLON || (BABYLON = {}));
  88611. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88612. var BABYLON;
  88613. (function (BABYLON) {
  88614. /**
  88615. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88616. */
  88617. var Gizmo = /** @class */ (function () {
  88618. /**
  88619. * Creates a gizmo
  88620. * @param gizmoLayer The utility layer the gizmo will be added to
  88621. */
  88622. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88623. var _this = this;
  88624. this.gizmoLayer = gizmoLayer;
  88625. /**
  88626. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88627. */
  88628. this.updateGizmoRotationToMatchAttachedMesh = true;
  88629. /**
  88630. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88631. */
  88632. this.updateGizmoPositionToMatchAttachedMesh = true;
  88633. /**
  88634. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88635. */
  88636. this._updateScale = true;
  88637. this._interactionsEnabled = true;
  88638. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  88639. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  88640. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  88641. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  88642. _this._rootMesh.scaling.set(dist, dist, dist);
  88643. }
  88644. if (_this.attachedMesh) {
  88645. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88646. if (!_this._rootMesh.rotationQuaternion) {
  88647. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  88648. }
  88649. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  88650. }
  88651. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  88652. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  88653. }
  88654. }
  88655. });
  88656. this.attachedMesh = null;
  88657. }
  88658. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  88659. /**
  88660. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  88661. * * When set, interactions will be enabled
  88662. */
  88663. get: function () {
  88664. return this._attachedMesh;
  88665. },
  88666. set: function (value) {
  88667. this._attachedMesh = value;
  88668. this._rootMesh.setEnabled(value ? true : false);
  88669. this._attachedMeshChanged(value);
  88670. },
  88671. enumerable: true,
  88672. configurable: true
  88673. });
  88674. Gizmo.prototype._attachedMeshChanged = function (value) {
  88675. };
  88676. /**
  88677. * Disposes of the gizmo
  88678. */
  88679. Gizmo.prototype.dispose = function () {
  88680. this._rootMesh.dispose();
  88681. if (this._beforeRenderObserver) {
  88682. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  88683. }
  88684. };
  88685. return Gizmo;
  88686. }());
  88687. BABYLON.Gizmo = Gizmo;
  88688. })(BABYLON || (BABYLON = {}));
  88689. //# sourceMappingURL=babylon.gizmo.js.map
  88690. var BABYLON;
  88691. (function (BABYLON) {
  88692. /**
  88693. * Single axis drag gizmo
  88694. */
  88695. var AxisDragGizmo = /** @class */ (function (_super) {
  88696. __extends(AxisDragGizmo, _super);
  88697. /**
  88698. * Creates an AxisDragGizmo
  88699. * @param gizmoLayer The utility layer the gizmo will be added to
  88700. * @param dragAxis The axis which the gizmo will be able to drag on
  88701. * @param color The color of the gizmo
  88702. */
  88703. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  88704. var _this = _super.call(this, gizmoLayer) || this;
  88705. _this._pointerObserver = null;
  88706. /**
  88707. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  88708. */
  88709. _this.snapDistance = 0;
  88710. /**
  88711. * Event that fires each time the gizmo snaps to a new location.
  88712. * * snapDistance is the the change in distance
  88713. */
  88714. _this.onSnapObservable = new BABYLON.Observable();
  88715. // Create Material
  88716. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88717. coloredMaterial.disableLighting = true;
  88718. coloredMaterial.emissiveColor = color;
  88719. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88720. hoverMaterial.disableLighting = true;
  88721. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88722. // Build mesh on root node
  88723. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88724. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88725. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88726. arrow.addChild(arrowMesh);
  88727. arrow.addChild(arrowTail);
  88728. // Position arrow pointing in its drag axis
  88729. arrowMesh.scaling.scaleInPlace(0.05);
  88730. arrowMesh.material = coloredMaterial;
  88731. arrowMesh.rotation.x = Math.PI / 2;
  88732. arrowMesh.position.z += 0.3;
  88733. arrowTail.rotation.x = Math.PI / 2;
  88734. arrowTail.material = coloredMaterial;
  88735. arrowTail.position.z += 0.15;
  88736. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88737. _this._rootMesh.addChild(arrow);
  88738. var currentSnapDragDistance = 0;
  88739. var tmpVector = new BABYLON.Vector3();
  88740. var tmpSnapEvent = { snapDistance: 0 };
  88741. // Add drag behavior to handle events when the gizmo is dragged
  88742. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88743. _this._dragBehavior.moveAttached = false;
  88744. _this._rootMesh.addBehavior(_this._dragBehavior);
  88745. _this._dragBehavior.onDragObservable.add(function (event) {
  88746. if (_this.attachedMesh) {
  88747. // Snapping logic
  88748. if (_this.snapDistance == 0) {
  88749. _this.attachedMesh.position.addInPlace(event.delta);
  88750. }
  88751. else {
  88752. currentSnapDragDistance += event.dragDistance;
  88753. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  88754. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  88755. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  88756. event.delta.normalizeToRef(tmpVector);
  88757. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  88758. _this.attachedMesh.position.addInPlace(tmpVector);
  88759. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  88760. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  88761. }
  88762. }
  88763. }
  88764. });
  88765. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  88766. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  88767. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88768. m.material = hoverMaterial;
  88769. });
  88770. }
  88771. else {
  88772. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88773. m.material = coloredMaterial;
  88774. });
  88775. }
  88776. });
  88777. return _this;
  88778. }
  88779. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  88780. if (this._dragBehavior) {
  88781. this._dragBehavior.enabled = value ? true : false;
  88782. }
  88783. };
  88784. /**
  88785. * Disposes of the gizmo
  88786. */
  88787. AxisDragGizmo.prototype.dispose = function () {
  88788. this.onSnapObservable.clear();
  88789. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  88790. this._dragBehavior.detach();
  88791. _super.prototype.dispose.call(this);
  88792. };
  88793. return AxisDragGizmo;
  88794. }(BABYLON.Gizmo));
  88795. BABYLON.AxisDragGizmo = AxisDragGizmo;
  88796. })(BABYLON || (BABYLON = {}));
  88797. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  88798. var BABYLON;
  88799. (function (BABYLON) {
  88800. /**
  88801. * Single axis scale gizmo
  88802. */
  88803. var AxisScaleGizmo = /** @class */ (function (_super) {
  88804. __extends(AxisScaleGizmo, _super);
  88805. /**
  88806. * Creates an AxisScaleGizmo
  88807. * @param gizmoLayer The utility layer the gizmo will be added to
  88808. * @param dragAxis The axis which the gizmo will be able to scale on
  88809. * @param color The color of the gizmo
  88810. */
  88811. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  88812. var _this = _super.call(this, gizmoLayer) || this;
  88813. _this._pointerObserver = null;
  88814. /**
  88815. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  88816. */
  88817. _this.snapDistance = 0;
  88818. /**
  88819. * Event that fires each time the gizmo snaps to a new location.
  88820. * * snapDistance is the the change in distance
  88821. */
  88822. _this.onSnapObservable = new BABYLON.Observable();
  88823. // Create Material
  88824. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88825. coloredMaterial.disableLighting = true;
  88826. coloredMaterial.emissiveColor = color;
  88827. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88828. hoverMaterial.disableLighting = true;
  88829. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88830. // Build mesh on root node
  88831. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88832. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  88833. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88834. arrow.addChild(arrowMesh);
  88835. arrow.addChild(arrowTail);
  88836. // Position arrow pointing in its drag axis
  88837. arrowMesh.scaling.scaleInPlace(0.1);
  88838. arrowMesh.material = coloredMaterial;
  88839. arrowMesh.rotation.x = Math.PI / 2;
  88840. arrowMesh.position.z += 0.3;
  88841. arrowTail.rotation.x = Math.PI / 2;
  88842. arrowTail.material = coloredMaterial;
  88843. arrowTail.position.z += 0.15;
  88844. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88845. _this._rootMesh.addChild(arrow);
  88846. // Add drag behavior to handle events when the gizmo is dragged
  88847. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88848. _this._dragBehavior.moveAttached = false;
  88849. _this._rootMesh.addBehavior(_this._dragBehavior);
  88850. var currentSnapDragDistance = 0;
  88851. var tmpVector = new BABYLON.Vector3();
  88852. var tmpSnapEvent = { snapDistance: 0 };
  88853. _this._dragBehavior.onDragObservable.add(function (event) {
  88854. if (_this.attachedMesh) {
  88855. // Snapping logic
  88856. var snapped = false;
  88857. var dragSteps = 0;
  88858. if (_this.snapDistance == 0) {
  88859. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  88860. }
  88861. else {
  88862. currentSnapDragDistance += event.dragDistance;
  88863. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  88864. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  88865. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  88866. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  88867. snapped = true;
  88868. }
  88869. else {
  88870. tmpVector.scaleInPlace(0);
  88871. }
  88872. }
  88873. var invertCount = 0;
  88874. if (_this.attachedMesh.scaling["x"] < 0) {
  88875. invertCount++;
  88876. }
  88877. if (_this.attachedMesh.scaling["y"] < 0) {
  88878. invertCount++;
  88879. }
  88880. if (_this.attachedMesh.scaling["z"] < 0) {
  88881. invertCount++;
  88882. }
  88883. if (invertCount % 2 == 0) {
  88884. _this.attachedMesh.scaling.addInPlace(tmpVector);
  88885. }
  88886. else {
  88887. _this.attachedMesh.scaling.subtractInPlace(tmpVector);
  88888. }
  88889. if (snapped) {
  88890. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  88891. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  88892. }
  88893. }
  88894. });
  88895. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  88896. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  88897. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88898. m.material = hoverMaterial;
  88899. });
  88900. }
  88901. else {
  88902. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88903. m.material = coloredMaterial;
  88904. });
  88905. }
  88906. });
  88907. return _this;
  88908. }
  88909. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  88910. if (this._dragBehavior) {
  88911. this._dragBehavior.enabled = value ? true : false;
  88912. }
  88913. };
  88914. /**
  88915. * Disposes of the gizmo
  88916. */
  88917. AxisScaleGizmo.prototype.dispose = function () {
  88918. this.onSnapObservable.clear();
  88919. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  88920. this._dragBehavior.detach();
  88921. _super.prototype.dispose.call(this);
  88922. };
  88923. return AxisScaleGizmo;
  88924. }(BABYLON.Gizmo));
  88925. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  88926. })(BABYLON || (BABYLON = {}));
  88927. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  88928. var BABYLON;
  88929. (function (BABYLON) {
  88930. /**
  88931. * Single plane rotation gizmo
  88932. */
  88933. var PlaneRotationGizmo = /** @class */ (function (_super) {
  88934. __extends(PlaneRotationGizmo, _super);
  88935. /**
  88936. * Creates a PlaneRotationGizmo
  88937. * @param gizmoLayer The utility layer the gizmo will be added to
  88938. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  88939. * @param color The color of the gizmo
  88940. */
  88941. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  88942. var _this = _super.call(this, gizmoLayer) || this;
  88943. _this._pointerObserver = null;
  88944. /**
  88945. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  88946. */
  88947. _this.snapDistance = 0;
  88948. /**
  88949. * Event that fires each time the gizmo snaps to a new location.
  88950. * * snapDistance is the the change in distance
  88951. */
  88952. _this.onSnapObservable = new BABYLON.Observable();
  88953. // Create Material
  88954. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88955. coloredMaterial.disableLighting = true;
  88956. coloredMaterial.emissiveColor = color;
  88957. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88958. hoverMaterial.disableLighting = true;
  88959. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88960. // Build mesh on root node
  88961. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88962. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  88963. // Position arrow pointing in its drag axis
  88964. rotationMesh.scaling.scaleInPlace(0.1);
  88965. rotationMesh.material = coloredMaterial;
  88966. rotationMesh.rotation.x = Math.PI / 2;
  88967. parentMesh.addChild(rotationMesh);
  88968. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  88969. _this._rootMesh.addChild(parentMesh);
  88970. // Add drag behavior to handle events when the gizmo is dragged
  88971. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  88972. _this._dragBehavior.moveAttached = false;
  88973. _this._rootMesh.addBehavior(_this._dragBehavior);
  88974. var lastDragPosition = null;
  88975. _this._dragBehavior.onDragStartObservable.add(function (e) {
  88976. if (_this.attachedMesh) {
  88977. lastDragPosition = e.dragPlanePoint;
  88978. }
  88979. });
  88980. var rotationMatrix = new BABYLON.Matrix();
  88981. var planeNormalTowardsCamera = new BABYLON.Vector3();
  88982. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  88983. var tmpSnapEvent = { snapDistance: 0 };
  88984. var currentSnapDragDistance = 0;
  88985. _this._dragBehavior.onDragObservable.add(function (event) {
  88986. if (_this.attachedMesh && lastDragPosition) {
  88987. if (!_this.attachedMesh.rotationQuaternion) {
  88988. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88989. }
  88990. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  88991. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  88992. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  88993. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  88994. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  88995. var angle = Math.atan2(cross.length(), dot);
  88996. planeNormalTowardsCamera.copyFrom(planeNormal);
  88997. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  88998. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88999. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89000. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89001. }
  89002. // Flip up vector depending on which side the camera is on
  89003. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89004. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89005. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89006. planeNormalTowardsCamera.scaleInPlace(-1);
  89007. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89008. }
  89009. }
  89010. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89011. if (halfCircleSide)
  89012. angle = -angle;
  89013. // Snapping logic
  89014. var snapped = false;
  89015. if (_this.snapDistance != 0) {
  89016. currentSnapDragDistance += angle;
  89017. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89018. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89019. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89020. angle = _this.snapDistance * dragSteps;
  89021. snapped = true;
  89022. }
  89023. else {
  89024. angle = 0;
  89025. }
  89026. }
  89027. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89028. var quaternionCoefficient = Math.sin(angle / 2);
  89029. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89030. // Rotate selected mesh quaternion over fixed axis
  89031. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89032. lastDragPosition = event.dragPlanePoint;
  89033. if (snapped) {
  89034. tmpSnapEvent.snapDistance = angle;
  89035. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89036. }
  89037. }
  89038. });
  89039. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89040. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89041. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89042. m.material = hoverMaterial;
  89043. });
  89044. }
  89045. else {
  89046. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89047. m.material = coloredMaterial;
  89048. });
  89049. }
  89050. });
  89051. return _this;
  89052. }
  89053. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89054. if (this._dragBehavior) {
  89055. this._dragBehavior.enabled = value ? true : false;
  89056. }
  89057. };
  89058. /**
  89059. * Disposes of the gizmo
  89060. */
  89061. PlaneRotationGizmo.prototype.dispose = function () {
  89062. this.onSnapObservable.clear();
  89063. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89064. this._dragBehavior.detach();
  89065. _super.prototype.dispose.call(this);
  89066. };
  89067. return PlaneRotationGizmo;
  89068. }(BABYLON.Gizmo));
  89069. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89070. })(BABYLON || (BABYLON = {}));
  89071. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89072. var BABYLON;
  89073. (function (BABYLON) {
  89074. /**
  89075. * Gizmo that enables dragging a mesh along 3 axis
  89076. */
  89077. var PositionGizmo = /** @class */ (function (_super) {
  89078. __extends(PositionGizmo, _super);
  89079. /**
  89080. * Creates a PositionGizmo
  89081. * @param gizmoLayer The utility layer the gizmo will be added to
  89082. */
  89083. function PositionGizmo(gizmoLayer) {
  89084. var _this = _super.call(this, gizmoLayer) || this;
  89085. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5));
  89086. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5));
  89087. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5));
  89088. _this.attachedMesh = null;
  89089. return _this;
  89090. }
  89091. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89092. set: function (mesh) {
  89093. if (this._xDrag) {
  89094. this._xDrag.attachedMesh = mesh;
  89095. this._yDrag.attachedMesh = mesh;
  89096. this._zDrag.attachedMesh = mesh;
  89097. }
  89098. },
  89099. enumerable: true,
  89100. configurable: true
  89101. });
  89102. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89103. get: function () {
  89104. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89105. },
  89106. set: function (value) {
  89107. if (this._xDrag) {
  89108. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89109. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89110. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89111. }
  89112. },
  89113. enumerable: true,
  89114. configurable: true
  89115. });
  89116. /**
  89117. * Disposes of the gizmo
  89118. */
  89119. PositionGizmo.prototype.dispose = function () {
  89120. this._xDrag.dispose();
  89121. this._yDrag.dispose();
  89122. this._zDrag.dispose();
  89123. };
  89124. return PositionGizmo;
  89125. }(BABYLON.Gizmo));
  89126. BABYLON.PositionGizmo = PositionGizmo;
  89127. })(BABYLON || (BABYLON = {}));
  89128. //# sourceMappingURL=babylon.positionGizmo.js.map
  89129. var BABYLON;
  89130. (function (BABYLON) {
  89131. /**
  89132. * Gizmo that enables rotating a mesh along 3 axis
  89133. */
  89134. var RotationGizmo = /** @class */ (function (_super) {
  89135. __extends(RotationGizmo, _super);
  89136. /**
  89137. * Creates a RotationGizmo
  89138. * @param gizmoLayer The utility layer the gizmo will be added to
  89139. */
  89140. function RotationGizmo(gizmoLayer) {
  89141. var _this = _super.call(this, gizmoLayer) || this;
  89142. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5));
  89143. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5));
  89144. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5));
  89145. _this.attachedMesh = null;
  89146. return _this;
  89147. }
  89148. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89149. set: function (mesh) {
  89150. if (this._xDrag) {
  89151. this._xDrag.attachedMesh = mesh;
  89152. this._yDrag.attachedMesh = mesh;
  89153. this._zDrag.attachedMesh = mesh;
  89154. }
  89155. },
  89156. enumerable: true,
  89157. configurable: true
  89158. });
  89159. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89160. get: function () {
  89161. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89162. },
  89163. set: function (value) {
  89164. if (this._xDrag) {
  89165. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89166. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89167. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89168. }
  89169. },
  89170. enumerable: true,
  89171. configurable: true
  89172. });
  89173. /**
  89174. * Disposes of the gizmo
  89175. */
  89176. RotationGizmo.prototype.dispose = function () {
  89177. this._xDrag.dispose();
  89178. this._yDrag.dispose();
  89179. this._zDrag.dispose();
  89180. };
  89181. return RotationGizmo;
  89182. }(BABYLON.Gizmo));
  89183. BABYLON.RotationGizmo = RotationGizmo;
  89184. })(BABYLON || (BABYLON = {}));
  89185. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89186. var BABYLON;
  89187. (function (BABYLON) {
  89188. /**
  89189. * Gizmo that enables scaling a mesh along 3 axis
  89190. */
  89191. var ScaleGizmo = /** @class */ (function (_super) {
  89192. __extends(ScaleGizmo, _super);
  89193. /**
  89194. * Creates a ScaleGizmo
  89195. * @param gizmoLayer The utility layer the gizmo will be added to
  89196. */
  89197. function ScaleGizmo(gizmoLayer) {
  89198. var _this = _super.call(this, gizmoLayer) || this;
  89199. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5));
  89200. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5));
  89201. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5));
  89202. _this.attachedMesh = null;
  89203. return _this;
  89204. }
  89205. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89206. set: function (mesh) {
  89207. if (this._xDrag) {
  89208. this._xDrag.attachedMesh = mesh;
  89209. this._yDrag.attachedMesh = mesh;
  89210. this._zDrag.attachedMesh = mesh;
  89211. }
  89212. },
  89213. enumerable: true,
  89214. configurable: true
  89215. });
  89216. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89217. get: function () {
  89218. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89219. },
  89220. set: function (value) {
  89221. if (this._xDrag) {
  89222. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89223. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89224. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89225. }
  89226. },
  89227. enumerable: true,
  89228. configurable: true
  89229. });
  89230. /**
  89231. * Disposes of the gizmo
  89232. */
  89233. ScaleGizmo.prototype.dispose = function () {
  89234. this._xDrag.dispose();
  89235. this._yDrag.dispose();
  89236. this._zDrag.dispose();
  89237. };
  89238. return ScaleGizmo;
  89239. }(BABYLON.Gizmo));
  89240. BABYLON.ScaleGizmo = ScaleGizmo;
  89241. })(BABYLON || (BABYLON = {}));
  89242. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89243. var BABYLON;
  89244. (function (BABYLON) {
  89245. /**
  89246. * Bounding box gizmo
  89247. */
  89248. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89249. __extends(BoundingBoxGizmo, _super);
  89250. /**
  89251. * Creates an BoundingBoxGizmo
  89252. * @param gizmoLayer The utility layer the gizmo will be added to
  89253. * @param color The color of the gizmo
  89254. */
  89255. function BoundingBoxGizmo(gizmoLayer, color) {
  89256. var _this = _super.call(this, gizmoLayer) || this;
  89257. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89258. _this._renderObserver = null;
  89259. _this._pointerObserver = null;
  89260. _this._scaleDragSpeed = 0.2;
  89261. _this._tmpQuaternion = new BABYLON.Quaternion();
  89262. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89263. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  89264. _this._updateScale = false;
  89265. // Create Materials
  89266. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89267. coloredMaterial.disableLighting = true;
  89268. coloredMaterial.emissiveColor = color;
  89269. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89270. hoverColoredMaterial.disableLighting = true;
  89271. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89272. // Build bounding box out of lines
  89273. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89274. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  89275. var lines = [];
  89276. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  89277. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89278. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89279. 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));
  89280. 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));
  89281. 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));
  89282. 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));
  89283. 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));
  89284. 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));
  89285. 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));
  89286. 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));
  89287. 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));
  89288. lines.forEach(function (l) {
  89289. l.color = color;
  89290. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  89291. l.isPickable = false;
  89292. _this._lineBoundingBox.addChild(l);
  89293. });
  89294. _this._rootMesh.addChild(_this._lineBoundingBox);
  89295. // Create rotation spheres
  89296. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89297. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  89298. var _loop_1 = function (i_1) {
  89299. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  89300. sphere.rotationQuaternion = new BABYLON.Quaternion();
  89301. sphere.material = coloredMaterial;
  89302. // Drag behavior
  89303. _dragBehavior = new BABYLON.PointerDragBehavior({});
  89304. _dragBehavior.moveAttached = false;
  89305. _dragBehavior.updateDragPlane = false;
  89306. sphere.addBehavior(_dragBehavior);
  89307. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  89308. var totalTurnAmountOfDrag = 0;
  89309. _dragBehavior.onDragStartObservable.add(function (event) {
  89310. startingTurnDirection.copyFrom(sphere.forward);
  89311. totalTurnAmountOfDrag = 0;
  89312. });
  89313. _dragBehavior.onDragObservable.add(function (event) {
  89314. if (_this.attachedMesh) {
  89315. var worldDragDirection = startingTurnDirection;
  89316. // Project the world right on to the drag plane
  89317. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  89318. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  89319. // project drag delta on to the resulting drag axis and rotate based on that
  89320. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  89321. // Rotate based on axis
  89322. if (!_this.attachedMesh.rotationQuaternion) {
  89323. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89324. }
  89325. // Do not allow the object to turn more than a full circle
  89326. totalTurnAmountOfDrag += projectDist;
  89327. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  89328. if (i_1 >= 8) {
  89329. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  89330. }
  89331. else if (i_1 >= 4) {
  89332. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  89333. }
  89334. else {
  89335. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  89336. }
  89337. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  89338. }
  89339. }
  89340. });
  89341. // Selection/deselection
  89342. _dragBehavior.onDragStartObservable.add(function () {
  89343. _this._selectNode(sphere);
  89344. });
  89345. _dragBehavior.onDragEndObservable.add(function () {
  89346. _this._selectNode(null);
  89347. });
  89348. this_1._rotateSpheresParent.addChild(sphere);
  89349. };
  89350. var this_1 = this, _dragBehavior;
  89351. for (var i_1 = 0; i_1 < 12; i_1++) {
  89352. _loop_1(i_1);
  89353. }
  89354. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89355. // Create scale cubes
  89356. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89357. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89358. for (var i = 0; i < 2; i++) {
  89359. for (var j = 0; j < 2; j++) {
  89360. var _loop_2 = function () {
  89361. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  89362. box.material = coloredMaterial;
  89363. // Dragging logic
  89364. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89365. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89366. _dragBehavior.moveAttached = false;
  89367. box.addBehavior(_dragBehavior);
  89368. _dragBehavior.onDragObservable.add(function (event) {
  89369. if (_this.attachedMesh) {
  89370. // Current boudning box dimensions
  89371. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  89372. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  89373. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  89374. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  89375. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  89376. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  89377. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  89378. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  89379. // Update scale and position
  89380. _this.attachedMesh.scaling.addInPlace(deltaScale);
  89381. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  89382. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  89383. }
  89384. });
  89385. // Selection/deselection
  89386. _dragBehavior.onDragStartObservable.add(function () {
  89387. _this._selectNode(box);
  89388. });
  89389. _dragBehavior.onDragEndObservable.add(function () {
  89390. _this._selectNode(null);
  89391. });
  89392. this_2._scaleBoxesParent.addChild(box);
  89393. };
  89394. var this_2 = this, _dragBehavior;
  89395. for (var k = 0; k < 2; k++) {
  89396. _loop_2();
  89397. }
  89398. }
  89399. }
  89400. _this._rootMesh.addChild(_this._scaleBoxesParent);
  89401. // Hover color change
  89402. var pointerIds = new Array();
  89403. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89404. if (!pointerIds[pointerInfo.event.pointerId]) {
  89405. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  89406. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  89407. pointerIds[pointerInfo.event.pointerId] = mesh;
  89408. mesh.material = hoverColoredMaterial;
  89409. }
  89410. });
  89411. }
  89412. else {
  89413. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  89414. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  89415. delete pointerIds[pointerInfo.event.pointerId];
  89416. }
  89417. }
  89418. });
  89419. // Update bounding box positions
  89420. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  89421. _this._updateBoundingBox();
  89422. });
  89423. _this._updateBoundingBox();
  89424. return _this;
  89425. }
  89426. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  89427. this._rotateSpheresParent.getChildMeshes()
  89428. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  89429. m.isVisible = (!selectedMesh || m == selectedMesh);
  89430. });
  89431. };
  89432. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  89433. if (this.attachedMesh) {
  89434. // Update bounding dimensions/positions
  89435. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  89436. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  89437. this._boundingDimensions.copyFrom(boundBoxDimensions);
  89438. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  89439. }
  89440. // Update rotation sphere locations
  89441. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  89442. for (var i = 0; i < 3; i++) {
  89443. for (var j = 0; j < 2; j++) {
  89444. for (var k = 0; k < 2; k++) {
  89445. var index = ((i * 4) + (j * 2)) + k;
  89446. if (i == 0) {
  89447. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89448. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89449. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89450. }
  89451. if (i == 1) {
  89452. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  89453. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89454. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89455. }
  89456. if (i == 2) {
  89457. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  89458. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89459. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89460. }
  89461. }
  89462. }
  89463. }
  89464. // Update scale box locations
  89465. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  89466. for (var i = 0; i < 2; i++) {
  89467. for (var j = 0; j < 2; j++) {
  89468. for (var k = 0; k < 2; k++) {
  89469. var index = ((i * 4) + (j * 2)) + k;
  89470. if (scaleBoxes[index]) {
  89471. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89472. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89473. }
  89474. }
  89475. }
  89476. }
  89477. };
  89478. /**
  89479. * Enables rotation on the specified axis and disables rotation on the others
  89480. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  89481. */
  89482. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  89483. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  89484. if (i < 4) {
  89485. m.setEnabled(axis.indexOf("x") != -1);
  89486. }
  89487. else if (i < 8) {
  89488. m.setEnabled(axis.indexOf("y") != -1);
  89489. }
  89490. else {
  89491. m.setEnabled(axis.indexOf("z") != -1);
  89492. }
  89493. });
  89494. };
  89495. /**
  89496. * Disposes of the gizmo
  89497. */
  89498. BoundingBoxGizmo.prototype.dispose = function () {
  89499. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89500. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  89501. this._lineBoundingBox.dispose();
  89502. this._rotateSpheresParent.dispose();
  89503. this._scaleBoxesParent.dispose();
  89504. _super.prototype.dispose.call(this);
  89505. };
  89506. return BoundingBoxGizmo;
  89507. }(BABYLON.Gizmo));
  89508. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  89509. })(BABYLON || (BABYLON = {}));
  89510. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  89511. var BABYLON;
  89512. (function (BABYLON) {
  89513. /**
  89514. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  89515. */
  89516. var GizmoManager = /** @class */ (function () {
  89517. /**
  89518. * Instatiates a gizmo manager
  89519. * @param scene the scene to overlay the gizmos on top of
  89520. * @param options If only a single gizmo should exist at one time
  89521. */
  89522. function GizmoManager(scene, options) {
  89523. var _this = this;
  89524. this.scene = scene;
  89525. // Set of gizmos that are currently in the scene for each mesh
  89526. this._gizmoSet = {};
  89527. this._pointerObserver = null;
  89528. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  89529. // Options parsing
  89530. if (!options) {
  89531. options = {};
  89532. }
  89533. if (options.singleGizmo === undefined) {
  89534. options.singleGizmo = true;
  89535. }
  89536. // Instatiate/dispose gizmos based on pointer actions
  89537. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  89538. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89539. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  89540. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  89541. if (options.singleGizmo) {
  89542. _this._clearGizmos();
  89543. }
  89544. // Enable gizmo when mesh is selected
  89545. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  89546. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89547. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89548. }
  89549. else {
  89550. if (!options.singleGizmo) {
  89551. // Disable gizmo when clicked again
  89552. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  89553. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  89554. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  89555. }
  89556. }
  89557. }
  89558. else {
  89559. if (options.singleGizmo) {
  89560. // Disable gizmo when clicked away
  89561. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89562. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  89563. if (gizmoPick && !gizmoPick.hit) {
  89564. _this._clearGizmos();
  89565. }
  89566. }
  89567. }
  89568. }
  89569. }
  89570. });
  89571. }
  89572. /**
  89573. * Disposes of the gizmo manager
  89574. */
  89575. GizmoManager.prototype.dispose = function () {
  89576. this.scene.onPointerObservable.remove(this._pointerObserver);
  89577. this._clearGizmos();
  89578. this._gizmoLayer.dispose();
  89579. };
  89580. GizmoManager.prototype._clearGizmos = function () {
  89581. for (var key in this._gizmoSet) {
  89582. if (this._gizmoSet.hasOwnProperty(key)) {
  89583. this._gizmoSet[key].positionGizmo.dispose();
  89584. this._gizmoSet[key].rotationGizmo.dispose();
  89585. delete this._gizmoSet[key];
  89586. }
  89587. }
  89588. };
  89589. return GizmoManager;
  89590. }());
  89591. BABYLON.GizmoManager = GizmoManager;
  89592. })(BABYLON || (BABYLON = {}));
  89593. //# sourceMappingURL=babylon.gizmoManager.js.map
  89594. var BABYLON;
  89595. (function (BABYLON) {
  89596. /**
  89597. * Defines a target to use with MorphTargetManager
  89598. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89599. */
  89600. var MorphTarget = /** @class */ (function () {
  89601. /**
  89602. * Creates a new MorphTarget
  89603. * @param name defines the name of the target
  89604. * @param influence defines the influence to use
  89605. */
  89606. function MorphTarget(
  89607. /** defines the name of the target */
  89608. name, influence, scene) {
  89609. if (influence === void 0) { influence = 0; }
  89610. if (scene === void 0) { scene = null; }
  89611. this.name = name;
  89612. /**
  89613. * Gets or sets the list of animations
  89614. */
  89615. this.animations = new Array();
  89616. this._positions = null;
  89617. this._normals = null;
  89618. this._tangents = null;
  89619. /**
  89620. * Observable raised when the influence changes
  89621. */
  89622. this.onInfluenceChanged = new BABYLON.Observable();
  89623. this._animationPropertiesOverride = null;
  89624. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89625. this.influence = influence;
  89626. }
  89627. Object.defineProperty(MorphTarget.prototype, "influence", {
  89628. /**
  89629. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  89630. */
  89631. get: function () {
  89632. return this._influence;
  89633. },
  89634. set: function (influence) {
  89635. if (this._influence === influence) {
  89636. return;
  89637. }
  89638. var previous = this._influence;
  89639. this._influence = influence;
  89640. if (this.onInfluenceChanged.hasObservers) {
  89641. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  89642. }
  89643. },
  89644. enumerable: true,
  89645. configurable: true
  89646. });
  89647. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  89648. /**
  89649. * Gets or sets the animation properties override
  89650. */
  89651. get: function () {
  89652. if (!this._animationPropertiesOverride && this._scene) {
  89653. return this._scene.animationPropertiesOverride;
  89654. }
  89655. return this._animationPropertiesOverride;
  89656. },
  89657. set: function (value) {
  89658. this._animationPropertiesOverride = value;
  89659. },
  89660. enumerable: true,
  89661. configurable: true
  89662. });
  89663. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  89664. /**
  89665. * Gets a boolean defining if the target contains position data
  89666. */
  89667. get: function () {
  89668. return !!this._positions;
  89669. },
  89670. enumerable: true,
  89671. configurable: true
  89672. });
  89673. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  89674. /**
  89675. * Gets a boolean defining if the target contains normal data
  89676. */
  89677. get: function () {
  89678. return !!this._normals;
  89679. },
  89680. enumerable: true,
  89681. configurable: true
  89682. });
  89683. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  89684. /**
  89685. * Gets a boolean defining if the target contains tangent data
  89686. */
  89687. get: function () {
  89688. return !!this._tangents;
  89689. },
  89690. enumerable: true,
  89691. configurable: true
  89692. });
  89693. /**
  89694. * Affects position data to this target
  89695. * @param data defines the position data to use
  89696. */
  89697. MorphTarget.prototype.setPositions = function (data) {
  89698. this._positions = data;
  89699. };
  89700. /**
  89701. * Gets the position data stored in this target
  89702. * @returns a FloatArray containing the position data (or null if not present)
  89703. */
  89704. MorphTarget.prototype.getPositions = function () {
  89705. return this._positions;
  89706. };
  89707. /**
  89708. * Affects normal data to this target
  89709. * @param data defines the normal data to use
  89710. */
  89711. MorphTarget.prototype.setNormals = function (data) {
  89712. this._normals = data;
  89713. };
  89714. /**
  89715. * Gets the normal data stored in this target
  89716. * @returns a FloatArray containing the normal data (or null if not present)
  89717. */
  89718. MorphTarget.prototype.getNormals = function () {
  89719. return this._normals;
  89720. };
  89721. /**
  89722. * Affects tangent data to this target
  89723. * @param data defines the tangent data to use
  89724. */
  89725. MorphTarget.prototype.setTangents = function (data) {
  89726. this._tangents = data;
  89727. };
  89728. /**
  89729. * Gets the tangent data stored in this target
  89730. * @returns a FloatArray containing the tangent data (or null if not present)
  89731. */
  89732. MorphTarget.prototype.getTangents = function () {
  89733. return this._tangents;
  89734. };
  89735. /**
  89736. * Serializes the current target into a Serialization object
  89737. * @returns the serialized object
  89738. */
  89739. MorphTarget.prototype.serialize = function () {
  89740. var serializationObject = {};
  89741. serializationObject.name = this.name;
  89742. serializationObject.influence = this.influence;
  89743. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  89744. if (this.hasNormals) {
  89745. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  89746. }
  89747. if (this.hasTangents) {
  89748. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  89749. }
  89750. // Animations
  89751. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  89752. return serializationObject;
  89753. };
  89754. // Statics
  89755. /**
  89756. * Creates a new target from serialized data
  89757. * @param serializationObject defines the serialized data to use
  89758. * @returns a new MorphTarget
  89759. */
  89760. MorphTarget.Parse = function (serializationObject) {
  89761. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  89762. result.setPositions(serializationObject.positions);
  89763. if (serializationObject.normals) {
  89764. result.setNormals(serializationObject.normals);
  89765. }
  89766. if (serializationObject.tangents) {
  89767. result.setTangents(serializationObject.tangents);
  89768. }
  89769. // Animations
  89770. if (serializationObject.animations) {
  89771. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  89772. var parsedAnimation = serializationObject.animations[animationIndex];
  89773. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  89774. }
  89775. }
  89776. return result;
  89777. };
  89778. /**
  89779. * Creates a MorphTarget from mesh data
  89780. * @param mesh defines the source mesh
  89781. * @param name defines the name to use for the new target
  89782. * @param influence defines the influence to attach to the target
  89783. * @returns a new MorphTarget
  89784. */
  89785. MorphTarget.FromMesh = function (mesh, name, influence) {
  89786. if (!name) {
  89787. name = mesh.name;
  89788. }
  89789. var result = new MorphTarget(name, influence, mesh.getScene());
  89790. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89791. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89792. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  89793. }
  89794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  89795. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  89796. }
  89797. return result;
  89798. };
  89799. return MorphTarget;
  89800. }());
  89801. BABYLON.MorphTarget = MorphTarget;
  89802. })(BABYLON || (BABYLON = {}));
  89803. //# sourceMappingURL=babylon.morphTarget.js.map
  89804. var BABYLON;
  89805. (function (BABYLON) {
  89806. /**
  89807. * This class is used to deform meshes using morphing between different targets
  89808. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89809. */
  89810. var MorphTargetManager = /** @class */ (function () {
  89811. /**
  89812. * Creates a new MorphTargetManager
  89813. * @param scene defines the current scene
  89814. */
  89815. function MorphTargetManager(scene) {
  89816. if (scene === void 0) { scene = null; }
  89817. this._targets = new Array();
  89818. this._targetObservable = new Array();
  89819. this._activeTargets = new BABYLON.SmartArray(16);
  89820. this._supportsNormals = false;
  89821. this._supportsTangents = false;
  89822. this._vertexCount = 0;
  89823. this._uniqueId = 0;
  89824. this._tempInfluences = new Array();
  89825. if (!scene) {
  89826. scene = BABYLON.Engine.LastCreatedScene;
  89827. }
  89828. this._scene = scene;
  89829. if (this._scene) {
  89830. this._scene.morphTargetManagers.push(this);
  89831. this._uniqueId = this._scene.getUniqueId();
  89832. }
  89833. }
  89834. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  89835. /**
  89836. * Gets the unique ID of this manager
  89837. */
  89838. get: function () {
  89839. return this._uniqueId;
  89840. },
  89841. enumerable: true,
  89842. configurable: true
  89843. });
  89844. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  89845. /**
  89846. * Gets the number of vertices handled by this manager
  89847. */
  89848. get: function () {
  89849. return this._vertexCount;
  89850. },
  89851. enumerable: true,
  89852. configurable: true
  89853. });
  89854. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  89855. /**
  89856. * Gets a boolean indicating if this manager supports morphing of normals
  89857. */
  89858. get: function () {
  89859. return this._supportsNormals;
  89860. },
  89861. enumerable: true,
  89862. configurable: true
  89863. });
  89864. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  89865. /**
  89866. * Gets a boolean indicating if this manager supports morphing of tangents
  89867. */
  89868. get: function () {
  89869. return this._supportsTangents;
  89870. },
  89871. enumerable: true,
  89872. configurable: true
  89873. });
  89874. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  89875. /**
  89876. * Gets the number of targets stored in this manager
  89877. */
  89878. get: function () {
  89879. return this._targets.length;
  89880. },
  89881. enumerable: true,
  89882. configurable: true
  89883. });
  89884. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  89885. /**
  89886. * Gets the number of influencers (ie. the number of targets with influences > 0)
  89887. */
  89888. get: function () {
  89889. return this._activeTargets.length;
  89890. },
  89891. enumerable: true,
  89892. configurable: true
  89893. });
  89894. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  89895. /**
  89896. * Gets the list of influences (one per target)
  89897. */
  89898. get: function () {
  89899. return this._influences;
  89900. },
  89901. enumerable: true,
  89902. configurable: true
  89903. });
  89904. /**
  89905. * Gets the active target at specified index. An active target is a target with an influence > 0
  89906. * @param index defines the index to check
  89907. * @returns the requested target
  89908. */
  89909. MorphTargetManager.prototype.getActiveTarget = function (index) {
  89910. return this._activeTargets.data[index];
  89911. };
  89912. /**
  89913. * Gets the target at specified index
  89914. * @param index defines the index to check
  89915. * @returns the requested target
  89916. */
  89917. MorphTargetManager.prototype.getTarget = function (index) {
  89918. return this._targets[index];
  89919. };
  89920. /**
  89921. * Add a new target to this manager
  89922. * @param target defines the target to add
  89923. */
  89924. MorphTargetManager.prototype.addTarget = function (target) {
  89925. var _this = this;
  89926. this._targets.push(target);
  89927. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  89928. _this._syncActiveTargets(needUpdate);
  89929. }));
  89930. this._syncActiveTargets(true);
  89931. };
  89932. /**
  89933. * Removes a target from the manager
  89934. * @param target defines the target to remove
  89935. */
  89936. MorphTargetManager.prototype.removeTarget = function (target) {
  89937. var index = this._targets.indexOf(target);
  89938. if (index >= 0) {
  89939. this._targets.splice(index, 1);
  89940. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  89941. this._syncActiveTargets(true);
  89942. }
  89943. };
  89944. /**
  89945. * Serializes the current manager into a Serialization object
  89946. * @returns the serialized object
  89947. */
  89948. MorphTargetManager.prototype.serialize = function () {
  89949. var serializationObject = {};
  89950. serializationObject.id = this.uniqueId;
  89951. serializationObject.targets = [];
  89952. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89953. var target = _a[_i];
  89954. serializationObject.targets.push(target.serialize());
  89955. }
  89956. return serializationObject;
  89957. };
  89958. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  89959. var influenceCount = 0;
  89960. this._activeTargets.reset();
  89961. this._supportsNormals = true;
  89962. this._supportsTangents = true;
  89963. this._vertexCount = 0;
  89964. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89965. var target = _a[_i];
  89966. this._activeTargets.push(target);
  89967. this._tempInfluences[influenceCount++] = target.influence;
  89968. var positions = target.getPositions();
  89969. if (positions) {
  89970. this._supportsNormals = this._supportsNormals && target.hasNormals;
  89971. this._supportsTangents = this._supportsTangents && target.hasTangents;
  89972. var vertexCount = positions.length / 3;
  89973. if (this._vertexCount === 0) {
  89974. this._vertexCount = vertexCount;
  89975. }
  89976. else if (this._vertexCount !== vertexCount) {
  89977. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  89978. return;
  89979. }
  89980. }
  89981. }
  89982. if (!this._influences || this._influences.length !== influenceCount) {
  89983. this._influences = new Float32Array(influenceCount);
  89984. }
  89985. for (var index = 0; index < influenceCount; index++) {
  89986. this._influences[index] = this._tempInfluences[index];
  89987. }
  89988. if (needUpdate) {
  89989. this.synchronize();
  89990. }
  89991. };
  89992. /**
  89993. * Syncrhonize the targets with all the meshes using this morph target manager
  89994. */
  89995. MorphTargetManager.prototype.synchronize = function () {
  89996. if (!this._scene) {
  89997. return;
  89998. }
  89999. // Flag meshes as dirty to resync with the active targets
  90000. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90001. var mesh = _a[_i];
  90002. if (mesh.morphTargetManager === this) {
  90003. mesh._syncGeometryWithMorphTargetManager();
  90004. }
  90005. }
  90006. };
  90007. // Statics
  90008. /**
  90009. * Creates a new MorphTargetManager from serialized data
  90010. * @param serializationObject defines the serialized data
  90011. * @param scene defines the hosting scene
  90012. * @returns the new MorphTargetManager
  90013. */
  90014. MorphTargetManager.Parse = function (serializationObject, scene) {
  90015. var result = new MorphTargetManager(scene);
  90016. result._uniqueId = serializationObject.id;
  90017. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90018. var targetData = _a[_i];
  90019. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90020. }
  90021. return result;
  90022. };
  90023. return MorphTargetManager;
  90024. }());
  90025. BABYLON.MorphTargetManager = MorphTargetManager;
  90026. })(BABYLON || (BABYLON = {}));
  90027. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90028. var BABYLON;
  90029. (function (BABYLON) {
  90030. var Octree = /** @class */ (function () {
  90031. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90032. if (maxDepth === void 0) { maxDepth = 2; }
  90033. this.maxDepth = maxDepth;
  90034. this.dynamicContent = new Array();
  90035. this._maxBlockCapacity = maxBlockCapacity || 64;
  90036. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90037. this._creationFunc = creationFunc;
  90038. }
  90039. // Methods
  90040. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90041. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90042. };
  90043. Octree.prototype.addMesh = function (entry) {
  90044. for (var index = 0; index < this.blocks.length; index++) {
  90045. var block = this.blocks[index];
  90046. block.addEntry(entry);
  90047. }
  90048. };
  90049. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90050. this._selectionContent.reset();
  90051. for (var index = 0; index < this.blocks.length; index++) {
  90052. var block = this.blocks[index];
  90053. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90054. }
  90055. if (allowDuplicate) {
  90056. this._selectionContent.concat(this.dynamicContent);
  90057. }
  90058. else {
  90059. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90060. }
  90061. return this._selectionContent;
  90062. };
  90063. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90064. this._selectionContent.reset();
  90065. for (var index = 0; index < this.blocks.length; index++) {
  90066. var block = this.blocks[index];
  90067. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90068. }
  90069. if (allowDuplicate) {
  90070. this._selectionContent.concat(this.dynamicContent);
  90071. }
  90072. else {
  90073. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90074. }
  90075. return this._selectionContent;
  90076. };
  90077. Octree.prototype.intersectsRay = function (ray) {
  90078. this._selectionContent.reset();
  90079. for (var index = 0; index < this.blocks.length; index++) {
  90080. var block = this.blocks[index];
  90081. block.intersectsRay(ray, this._selectionContent);
  90082. }
  90083. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90084. return this._selectionContent;
  90085. };
  90086. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  90087. target.blocks = new Array();
  90088. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  90089. // Segmenting space
  90090. for (var x = 0; x < 2; x++) {
  90091. for (var y = 0; y < 2; y++) {
  90092. for (var z = 0; z < 2; z++) {
  90093. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  90094. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  90095. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  90096. block.addEntries(entries);
  90097. target.blocks.push(block);
  90098. }
  90099. }
  90100. }
  90101. };
  90102. Octree.CreationFuncForMeshes = function (entry, block) {
  90103. var boundingInfo = entry.getBoundingInfo();
  90104. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90105. block.entries.push(entry);
  90106. }
  90107. };
  90108. Octree.CreationFuncForSubMeshes = function (entry, block) {
  90109. var boundingInfo = entry.getBoundingInfo();
  90110. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90111. block.entries.push(entry);
  90112. }
  90113. };
  90114. return Octree;
  90115. }());
  90116. BABYLON.Octree = Octree;
  90117. })(BABYLON || (BABYLON = {}));
  90118. //# sourceMappingURL=babylon.octree.js.map
  90119. var BABYLON;
  90120. (function (BABYLON) {
  90121. var OctreeBlock = /** @class */ (function () {
  90122. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  90123. this.entries = new Array();
  90124. this._boundingVectors = new Array();
  90125. this._capacity = capacity;
  90126. this._depth = depth;
  90127. this._maxDepth = maxDepth;
  90128. this._creationFunc = creationFunc;
  90129. this._minPoint = minPoint;
  90130. this._maxPoint = maxPoint;
  90131. this._boundingVectors.push(minPoint.clone());
  90132. this._boundingVectors.push(maxPoint.clone());
  90133. this._boundingVectors.push(minPoint.clone());
  90134. this._boundingVectors[2].x = maxPoint.x;
  90135. this._boundingVectors.push(minPoint.clone());
  90136. this._boundingVectors[3].y = maxPoint.y;
  90137. this._boundingVectors.push(minPoint.clone());
  90138. this._boundingVectors[4].z = maxPoint.z;
  90139. this._boundingVectors.push(maxPoint.clone());
  90140. this._boundingVectors[5].z = minPoint.z;
  90141. this._boundingVectors.push(maxPoint.clone());
  90142. this._boundingVectors[6].x = minPoint.x;
  90143. this._boundingVectors.push(maxPoint.clone());
  90144. this._boundingVectors[7].y = minPoint.y;
  90145. }
  90146. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  90147. // Property
  90148. get: function () {
  90149. return this._capacity;
  90150. },
  90151. enumerable: true,
  90152. configurable: true
  90153. });
  90154. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  90155. get: function () {
  90156. return this._minPoint;
  90157. },
  90158. enumerable: true,
  90159. configurable: true
  90160. });
  90161. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  90162. get: function () {
  90163. return this._maxPoint;
  90164. },
  90165. enumerable: true,
  90166. configurable: true
  90167. });
  90168. // Methods
  90169. OctreeBlock.prototype.addEntry = function (entry) {
  90170. if (this.blocks) {
  90171. for (var index = 0; index < this.blocks.length; index++) {
  90172. var block = this.blocks[index];
  90173. block.addEntry(entry);
  90174. }
  90175. return;
  90176. }
  90177. this._creationFunc(entry, this);
  90178. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  90179. this.createInnerBlocks();
  90180. }
  90181. };
  90182. OctreeBlock.prototype.addEntries = function (entries) {
  90183. for (var index = 0; index < entries.length; index++) {
  90184. var mesh = entries[index];
  90185. this.addEntry(mesh);
  90186. }
  90187. };
  90188. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  90189. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  90190. if (this.blocks) {
  90191. for (var index = 0; index < this.blocks.length; index++) {
  90192. var block = this.blocks[index];
  90193. block.select(frustumPlanes, selection, allowDuplicate);
  90194. }
  90195. return;
  90196. }
  90197. if (allowDuplicate) {
  90198. selection.concat(this.entries);
  90199. }
  90200. else {
  90201. selection.concatWithNoDuplicate(this.entries);
  90202. }
  90203. }
  90204. };
  90205. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  90206. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  90207. if (this.blocks) {
  90208. for (var index = 0; index < this.blocks.length; index++) {
  90209. var block = this.blocks[index];
  90210. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  90211. }
  90212. return;
  90213. }
  90214. if (allowDuplicate) {
  90215. selection.concat(this.entries);
  90216. }
  90217. else {
  90218. selection.concatWithNoDuplicate(this.entries);
  90219. }
  90220. }
  90221. };
  90222. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  90223. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  90224. if (this.blocks) {
  90225. for (var index = 0; index < this.blocks.length; index++) {
  90226. var block = this.blocks[index];
  90227. block.intersectsRay(ray, selection);
  90228. }
  90229. return;
  90230. }
  90231. selection.concatWithNoDuplicate(this.entries);
  90232. }
  90233. };
  90234. OctreeBlock.prototype.createInnerBlocks = function () {
  90235. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  90236. };
  90237. return OctreeBlock;
  90238. }());
  90239. BABYLON.OctreeBlock = OctreeBlock;
  90240. })(BABYLON || (BABYLON = {}));
  90241. //# sourceMappingURL=babylon.octreeBlock.js.map
  90242. var BABYLON;
  90243. (function (BABYLON) {
  90244. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  90245. __extends(VRDistortionCorrectionPostProcess, _super);
  90246. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  90247. var _this = _super.call(this, name, "vrDistortionCorrection", [
  90248. 'LensCenter',
  90249. 'Scale',
  90250. 'ScaleIn',
  90251. 'HmdWarpParam'
  90252. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  90253. _this._isRightEye = isRightEye;
  90254. _this._distortionFactors = vrMetrics.distortionK;
  90255. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  90256. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  90257. _this.adaptScaleToCurrentViewport = true;
  90258. _this.onSizeChangedObservable.add(function () {
  90259. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  90260. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  90261. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  90262. });
  90263. _this.onApplyObservable.add(function (effect) {
  90264. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  90265. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  90266. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  90267. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  90268. });
  90269. return _this;
  90270. }
  90271. return VRDistortionCorrectionPostProcess;
  90272. }(BABYLON.PostProcess));
  90273. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  90274. })(BABYLON || (BABYLON = {}));
  90275. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  90276. var BABYLON;
  90277. (function (BABYLON) {
  90278. /**
  90279. * Postprocess used to generate anaglyphic rendering
  90280. */
  90281. var AnaglyphPostProcess = /** @class */ (function (_super) {
  90282. __extends(AnaglyphPostProcess, _super);
  90283. /**
  90284. * Creates a new AnaglyphPostProcess
  90285. * @param name defines postprocess name
  90286. * @param options defines creation options or target ratio scale
  90287. * @param rigCameras defines cameras using this postprocess
  90288. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  90289. * @param engine defines hosting engine
  90290. * @param reusable defines if the postprocess will be reused multiple times per frame
  90291. */
  90292. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  90293. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  90294. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90295. _this.onApplyObservable.add(function (effect) {
  90296. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  90297. });
  90298. return _this;
  90299. }
  90300. return AnaglyphPostProcess;
  90301. }(BABYLON.PostProcess));
  90302. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  90303. })(BABYLON || (BABYLON = {}));
  90304. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  90305. var BABYLON;
  90306. (function (BABYLON) {
  90307. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  90308. __extends(StereoscopicInterlacePostProcess, _super);
  90309. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  90310. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  90311. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90312. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90313. _this.onSizeChangedObservable.add(function () {
  90314. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90315. });
  90316. _this.onApplyObservable.add(function (effect) {
  90317. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  90318. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  90319. });
  90320. return _this;
  90321. }
  90322. return StereoscopicInterlacePostProcess;
  90323. }(BABYLON.PostProcess));
  90324. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  90325. })(BABYLON || (BABYLON = {}));
  90326. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  90327. var BABYLON;
  90328. (function (BABYLON) {
  90329. /**
  90330. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  90331. * Screen rotation is taken into account.
  90332. */
  90333. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  90334. function FreeCameraDeviceOrientationInput() {
  90335. var _this = this;
  90336. this._screenOrientationAngle = 0;
  90337. this._screenQuaternion = new BABYLON.Quaternion();
  90338. this._alpha = 0;
  90339. this._beta = 0;
  90340. this._gamma = 0;
  90341. this._orientationChanged = function () {
  90342. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  90343. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  90344. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  90345. };
  90346. this._deviceOrientation = function (evt) {
  90347. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  90348. _this._beta = evt.beta !== null ? evt.beta : 0;
  90349. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  90350. };
  90351. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  90352. this._orientationChanged();
  90353. }
  90354. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  90355. get: function () {
  90356. return this._camera;
  90357. },
  90358. set: function (camera) {
  90359. this._camera = camera;
  90360. if (this._camera != null && !this._camera.rotationQuaternion) {
  90361. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  90362. }
  90363. },
  90364. enumerable: true,
  90365. configurable: true
  90366. });
  90367. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90368. window.addEventListener("orientationchange", this._orientationChanged);
  90369. window.addEventListener("deviceorientation", this._deviceOrientation);
  90370. //In certain cases, the attach control is called AFTER orientation was changed,
  90371. //So this is needed.
  90372. this._orientationChanged();
  90373. };
  90374. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  90375. window.removeEventListener("orientationchange", this._orientationChanged);
  90376. window.removeEventListener("deviceorientation", this._deviceOrientation);
  90377. };
  90378. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  90379. //if no device orientation provided, don't update the rotation.
  90380. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  90381. if (!this._alpha)
  90382. return;
  90383. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  90384. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  90385. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  90386. //Mirror on XY Plane
  90387. this._camera.rotationQuaternion.z *= -1;
  90388. this._camera.rotationQuaternion.w *= -1;
  90389. };
  90390. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  90391. return "FreeCameraDeviceOrientationInput";
  90392. };
  90393. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  90394. return "deviceOrientation";
  90395. };
  90396. return FreeCameraDeviceOrientationInput;
  90397. }());
  90398. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  90399. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  90400. })(BABYLON || (BABYLON = {}));
  90401. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  90402. var BABYLON;
  90403. (function (BABYLON) {
  90404. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  90405. function ArcRotateCameraVRDeviceOrientationInput() {
  90406. this.alphaCorrection = 1;
  90407. this.betaCorrection = 1;
  90408. this.gammaCorrection = 1;
  90409. this._alpha = 0;
  90410. this._gamma = 0;
  90411. this._dirty = false;
  90412. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  90413. }
  90414. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90415. this.camera.attachControl(element, noPreventDefault);
  90416. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  90417. };
  90418. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  90419. if (evt.alpha !== null) {
  90420. this._alpha = +evt.alpha | 0;
  90421. }
  90422. if (evt.gamma !== null) {
  90423. this._gamma = +evt.gamma | 0;
  90424. }
  90425. this._dirty = true;
  90426. };
  90427. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  90428. if (this._dirty) {
  90429. this._dirty = false;
  90430. if (this._gamma < 0) {
  90431. this._gamma = 180 + this._gamma;
  90432. }
  90433. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  90434. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  90435. }
  90436. };
  90437. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  90438. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  90439. };
  90440. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  90441. return "ArcRotateCameraVRDeviceOrientationInput";
  90442. };
  90443. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  90444. return "VRDeviceOrientation";
  90445. };
  90446. return ArcRotateCameraVRDeviceOrientationInput;
  90447. }());
  90448. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  90449. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  90450. })(BABYLON || (BABYLON = {}));
  90451. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  90452. var BABYLON;
  90453. (function (BABYLON) {
  90454. var VRCameraMetrics = /** @class */ (function () {
  90455. function VRCameraMetrics() {
  90456. this.compensateDistortion = true;
  90457. }
  90458. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  90459. get: function () {
  90460. return this.hResolution / (2 * this.vResolution);
  90461. },
  90462. enumerable: true,
  90463. configurable: true
  90464. });
  90465. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  90466. get: function () {
  90467. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  90468. },
  90469. enumerable: true,
  90470. configurable: true
  90471. });
  90472. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  90473. get: function () {
  90474. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90475. var h = (4 * meters) / this.hScreenSize;
  90476. return BABYLON.Matrix.Translation(h, 0, 0);
  90477. },
  90478. enumerable: true,
  90479. configurable: true
  90480. });
  90481. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  90482. get: function () {
  90483. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90484. var h = (4 * meters) / this.hScreenSize;
  90485. return BABYLON.Matrix.Translation(-h, 0, 0);
  90486. },
  90487. enumerable: true,
  90488. configurable: true
  90489. });
  90490. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  90491. get: function () {
  90492. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  90493. },
  90494. enumerable: true,
  90495. configurable: true
  90496. });
  90497. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  90498. get: function () {
  90499. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  90500. },
  90501. enumerable: true,
  90502. configurable: true
  90503. });
  90504. VRCameraMetrics.GetDefault = function () {
  90505. var result = new VRCameraMetrics();
  90506. result.hResolution = 1280;
  90507. result.vResolution = 800;
  90508. result.hScreenSize = 0.149759993;
  90509. result.vScreenSize = 0.0935999975;
  90510. result.vScreenCenter = 0.0467999987;
  90511. result.eyeToScreenDistance = 0.0410000011;
  90512. result.lensSeparationDistance = 0.0635000020;
  90513. result.interpupillaryDistance = 0.0640000030;
  90514. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  90515. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  90516. result.postProcessScaleFactor = 1.714605507808412;
  90517. result.lensCenterOffset = 0.151976421;
  90518. return result;
  90519. };
  90520. return VRCameraMetrics;
  90521. }());
  90522. BABYLON.VRCameraMetrics = VRCameraMetrics;
  90523. })(BABYLON || (BABYLON = {}));
  90524. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  90525. var BABYLON;
  90526. (function (BABYLON) {
  90527. /**
  90528. * This represents a WebVR camera.
  90529. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  90530. * @example http://doc.babylonjs.com/how_to/webvr_camera
  90531. */
  90532. var WebVRFreeCamera = /** @class */ (function (_super) {
  90533. __extends(WebVRFreeCamera, _super);
  90534. /**
  90535. * Instantiates a WebVRFreeCamera.
  90536. * @param name The name of the WebVRFreeCamera
  90537. * @param position The starting anchor position for the camera
  90538. * @param scene The scene the camera belongs to
  90539. * @param webVROptions a set of customizable options for the webVRCamera
  90540. */
  90541. function WebVRFreeCamera(name, position, scene, webVROptions) {
  90542. if (webVROptions === void 0) { webVROptions = {}; }
  90543. var _this = _super.call(this, name, position, scene) || this;
  90544. _this.webVROptions = webVROptions;
  90545. /**
  90546. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  90547. */
  90548. _this._vrDevice = null;
  90549. /**
  90550. * The rawPose of the vrDevice.
  90551. */
  90552. _this.rawPose = null;
  90553. _this._specsVersion = "1.1";
  90554. _this._attached = false;
  90555. _this._descendants = [];
  90556. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  90557. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  90558. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  90559. _this._standingMatrix = null;
  90560. /**
  90561. * Represents device position in babylon space.
  90562. */
  90563. _this.devicePosition = BABYLON.Vector3.Zero();
  90564. /**
  90565. * Represents device rotation in babylon space.
  90566. */
  90567. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  90568. /**
  90569. * The scale of the device to be used when translating from device space to babylon space.
  90570. */
  90571. _this.deviceScaleFactor = 1;
  90572. _this._deviceToWorld = BABYLON.Matrix.Identity();
  90573. _this._worldToDevice = BABYLON.Matrix.Identity();
  90574. /**
  90575. * References to the webVR controllers for the vrDevice.
  90576. */
  90577. _this.controllers = [];
  90578. /**
  90579. * Emits an event when a controller is attached.
  90580. */
  90581. _this.onControllersAttachedObservable = new BABYLON.Observable();
  90582. /**
  90583. * Emits an event when a controller's mesh has been loaded;
  90584. */
  90585. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90586. /**
  90587. * If the rig cameras be used as parent instead of this camera.
  90588. */
  90589. _this.rigParenting = true;
  90590. _this._defaultHeight = undefined;
  90591. _this._workingVector = BABYLON.Vector3.Zero();
  90592. _this._oneVector = BABYLON.Vector3.One();
  90593. _this._workingMatrix = BABYLON.Matrix.Identity();
  90594. _this._cache.position = BABYLON.Vector3.Zero();
  90595. if (webVROptions.defaultHeight) {
  90596. _this._defaultHeight = webVROptions.defaultHeight;
  90597. _this.position.y = _this._defaultHeight;
  90598. }
  90599. _this.minZ = 0.1;
  90600. //legacy support - the compensation boolean was removed.
  90601. if (arguments.length === 5) {
  90602. _this.webVROptions = arguments[4];
  90603. }
  90604. // default webVR options
  90605. if (_this.webVROptions.trackPosition == undefined) {
  90606. _this.webVROptions.trackPosition = true;
  90607. }
  90608. if (_this.webVROptions.controllerMeshes == undefined) {
  90609. _this.webVROptions.controllerMeshes = true;
  90610. }
  90611. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  90612. _this.webVROptions.defaultLightingOnControllers = true;
  90613. }
  90614. _this.rotationQuaternion = new BABYLON.Quaternion();
  90615. if (_this.webVROptions && _this.webVROptions.positionScale) {
  90616. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  90617. }
  90618. //enable VR
  90619. var engine = _this.getEngine();
  90620. _this._onVREnabled = function (success) { if (success) {
  90621. _this.initControllers();
  90622. } };
  90623. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  90624. engine.initWebVR().add(function (event) {
  90625. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  90626. return;
  90627. }
  90628. _this._vrDevice = event.vrDisplay;
  90629. //reset the rig parameters.
  90630. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  90631. if (_this._attached) {
  90632. _this.getEngine().enableVR();
  90633. }
  90634. });
  90635. if (typeof (VRFrameData) !== "undefined")
  90636. _this._frameData = new VRFrameData();
  90637. /**
  90638. * The idea behind the following lines:
  90639. * objects that have the camera as parent should actually have the rig cameras as a parent.
  90640. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  90641. * the second will not show it correctly.
  90642. *
  90643. * To solve this - each object that has the camera as parent will be added to a protected array.
  90644. * When the rig camera renders, it will take this array and set all of those to be its children.
  90645. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  90646. * Amazing!
  90647. */
  90648. scene.onBeforeCameraRenderObservable.add(function (camera) {
  90649. if (camera.parent === _this && _this.rigParenting) {
  90650. _this._descendants = _this.getDescendants(true, function (n) {
  90651. // don't take the cameras or the controllers!
  90652. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  90653. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  90654. return !isController && !isRigCamera;
  90655. });
  90656. _this._descendants.forEach(function (node) {
  90657. node.parent = camera;
  90658. });
  90659. }
  90660. });
  90661. scene.onAfterCameraRenderObservable.add(function (camera) {
  90662. if (camera.parent === _this && _this.rigParenting) {
  90663. _this._descendants.forEach(function (node) {
  90664. node.parent = _this;
  90665. });
  90666. }
  90667. });
  90668. return _this;
  90669. }
  90670. /**
  90671. * Gets the device distance from the ground in meters.
  90672. * @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.
  90673. */
  90674. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  90675. if (this._standingMatrix) {
  90676. // Add standing matrix offset to get real offset from ground in room
  90677. this._standingMatrix.getTranslationToRef(this._workingVector);
  90678. return this._deviceRoomPosition.y + this._workingVector.y;
  90679. }
  90680. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  90681. return this._defaultHeight || 0;
  90682. };
  90683. /**
  90684. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90685. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  90686. */
  90687. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  90688. var _this = this;
  90689. if (callback === void 0) { callback = function (bool) { }; }
  90690. // Use standing matrix if available
  90691. this.getEngine().initWebVRAsync().then(function (result) {
  90692. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  90693. callback(false);
  90694. }
  90695. else {
  90696. _this._standingMatrix = new BABYLON.Matrix();
  90697. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  90698. if (!_this.getScene().useRightHandedSystem) {
  90699. [2, 6, 8, 9, 14].forEach(function (num) {
  90700. if (_this._standingMatrix) {
  90701. _this._standingMatrix.m[num] *= -1;
  90702. }
  90703. });
  90704. }
  90705. callback(true);
  90706. }
  90707. });
  90708. };
  90709. /**
  90710. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90711. * @returns A promise with a boolean set to if the standing matrix is supported.
  90712. */
  90713. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  90714. var _this = this;
  90715. return new Promise(function (res, rej) {
  90716. _this.useStandingMatrix(function (supported) {
  90717. res(supported);
  90718. });
  90719. });
  90720. };
  90721. /**
  90722. * Disposes the camera
  90723. */
  90724. WebVRFreeCamera.prototype.dispose = function () {
  90725. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  90726. _super.prototype.dispose.call(this);
  90727. };
  90728. /**
  90729. * Gets a vrController by name.
  90730. * @param name The name of the controller to retreive
  90731. * @returns the controller matching the name specified or null if not found
  90732. */
  90733. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  90734. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  90735. var gp = _a[_i];
  90736. if (gp.hand === name) {
  90737. return gp;
  90738. }
  90739. }
  90740. return null;
  90741. };
  90742. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  90743. /**
  90744. * The controller corrisponding to the users left hand.
  90745. */
  90746. get: function () {
  90747. if (!this._leftController) {
  90748. this._leftController = this.getControllerByName("left");
  90749. }
  90750. return this._leftController;
  90751. },
  90752. enumerable: true,
  90753. configurable: true
  90754. });
  90755. ;
  90756. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  90757. /**
  90758. * The controller corrisponding to the users right hand.
  90759. */
  90760. get: function () {
  90761. if (!this._rightController) {
  90762. this._rightController = this.getControllerByName("right");
  90763. }
  90764. return this._rightController;
  90765. },
  90766. enumerable: true,
  90767. configurable: true
  90768. });
  90769. ;
  90770. /**
  90771. * Casts a ray forward from the vrCamera's gaze.
  90772. * @param length Length of the ray (default: 100)
  90773. * @returns the ray corrisponding to the gaze
  90774. */
  90775. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  90776. if (length === void 0) { length = 100; }
  90777. if (this.leftCamera) {
  90778. // Use left eye to avoid computation to compute center on every call
  90779. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  90780. }
  90781. else {
  90782. return _super.prototype.getForwardRay.call(this, length);
  90783. }
  90784. };
  90785. /**
  90786. * Updates the camera based on device's frame data
  90787. */
  90788. WebVRFreeCamera.prototype._checkInputs = function () {
  90789. if (this._vrDevice && this._vrDevice.isPresenting) {
  90790. this._vrDevice.getFrameData(this._frameData);
  90791. this.updateFromDevice(this._frameData.pose);
  90792. }
  90793. _super.prototype._checkInputs.call(this);
  90794. };
  90795. /**
  90796. * Updates the poseControlled values based on the input device pose.
  90797. * @param poseData Pose coming from the device
  90798. */
  90799. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  90800. if (poseData && poseData.orientation) {
  90801. this.rawPose = poseData;
  90802. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  90803. if (this.getScene().useRightHandedSystem) {
  90804. this._deviceRoomRotationQuaternion.z *= -1;
  90805. this._deviceRoomRotationQuaternion.w *= -1;
  90806. }
  90807. if (this.webVROptions.trackPosition && this.rawPose.position) {
  90808. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  90809. if (this.getScene().useRightHandedSystem) {
  90810. this._deviceRoomPosition.z *= -1;
  90811. }
  90812. }
  90813. }
  90814. };
  90815. /**
  90816. * WebVR's attach control will start broadcasting frames to the device.
  90817. * Note that in certain browsers (chrome for example) this function must be called
  90818. * within a user-interaction callback. Example:
  90819. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  90820. *
  90821. * @param element html element to attach the vrDevice to
  90822. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  90823. */
  90824. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  90825. _super.prototype.attachControl.call(this, element, noPreventDefault);
  90826. this._attached = true;
  90827. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  90828. if (this._vrDevice) {
  90829. this.getEngine().enableVR();
  90830. }
  90831. };
  90832. /**
  90833. * Detaches the camera from the html element and disables VR
  90834. *
  90835. * @param element html element to detach from
  90836. */
  90837. WebVRFreeCamera.prototype.detachControl = function (element) {
  90838. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  90839. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  90840. _super.prototype.detachControl.call(this, element);
  90841. this._attached = false;
  90842. this.getEngine().disableVR();
  90843. };
  90844. /**
  90845. * @returns the name of this class
  90846. */
  90847. WebVRFreeCamera.prototype.getClassName = function () {
  90848. return "WebVRFreeCamera";
  90849. };
  90850. /**
  90851. * Calls resetPose on the vrDisplay
  90852. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  90853. */
  90854. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  90855. //uses the vrDisplay's "resetPose()".
  90856. //pitch and roll won't be affected.
  90857. this._vrDevice.resetPose();
  90858. };
  90859. /**
  90860. * Updates the rig cameras (left and right eye)
  90861. */
  90862. WebVRFreeCamera.prototype._updateRigCameras = function () {
  90863. var camLeft = this._rigCameras[0];
  90864. var camRight = this._rigCameras[1];
  90865. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90866. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90867. camLeft.position.copyFrom(this._deviceRoomPosition);
  90868. camRight.position.copyFrom(this._deviceRoomPosition);
  90869. };
  90870. /**
  90871. * Updates the cached values of the camera
  90872. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  90873. */
  90874. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  90875. var _this = this;
  90876. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  90877. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  90878. if (!this.updateCacheCalled) {
  90879. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  90880. this.updateCacheCalled = true;
  90881. this.update();
  90882. }
  90883. // Set working vector to the device position in room space rotated by the new rotation
  90884. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  90885. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  90886. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  90887. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  90888. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  90889. // Add translation from anchor position
  90890. this._deviceToWorld.getTranslationToRef(this._workingVector);
  90891. this._workingVector.addInPlace(this.position);
  90892. this._workingVector.subtractInPlace(this._cache.position);
  90893. this._deviceToWorld.setTranslation(this._workingVector);
  90894. // Set an inverted matrix to be used when updating the camera
  90895. this._deviceToWorld.invertToRef(this._worldToDevice);
  90896. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  90897. this.controllers.forEach(function (controller) {
  90898. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  90899. controller.update();
  90900. });
  90901. }
  90902. if (!ignoreParentClass) {
  90903. _super.prototype._updateCache.call(this);
  90904. }
  90905. this.updateCacheCalled = false;
  90906. };
  90907. /**
  90908. * Updates the current device position and rotation in the babylon world
  90909. */
  90910. WebVRFreeCamera.prototype.update = function () {
  90911. // Get current device position in babylon world
  90912. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  90913. // Get current device rotation in babylon world
  90914. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  90915. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  90916. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  90917. _super.prototype.update.call(this);
  90918. };
  90919. /**
  90920. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  90921. * @returns an identity matrix
  90922. */
  90923. WebVRFreeCamera.prototype._getViewMatrix = function () {
  90924. return BABYLON.Matrix.Identity();
  90925. };
  90926. /**
  90927. * This function is called by the two RIG cameras.
  90928. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  90929. */
  90930. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  90931. var _this = this;
  90932. // Update the parent camera prior to using a child camera to avoid desynchronization
  90933. var parentCamera = this._cameraRigParams["parentCamera"];
  90934. parentCamera._updateCache();
  90935. //WebVR 1.1
  90936. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  90937. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  90938. if (!this.getScene().useRightHandedSystem) {
  90939. [2, 6, 8, 9, 14].forEach(function (num) {
  90940. _this._webvrViewMatrix.m[num] *= -1;
  90941. });
  90942. }
  90943. // update the camera rotation matrix
  90944. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  90945. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  90946. // Computing target and final matrix
  90947. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  90948. // should the view matrix be updated with scale and position offset?
  90949. if (parentCamera.deviceScaleFactor !== 1) {
  90950. this._webvrViewMatrix.invert();
  90951. // scale the position, if set
  90952. if (parentCamera.deviceScaleFactor) {
  90953. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  90954. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  90955. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  90956. }
  90957. this._webvrViewMatrix.invert();
  90958. }
  90959. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  90960. // Compute global position
  90961. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  90962. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  90963. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  90964. this._workingMatrix.getTranslationToRef(this._globalPosition);
  90965. this._markSyncedWithParent();
  90966. return this._webvrViewMatrix;
  90967. };
  90968. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  90969. var _this = this;
  90970. var parentCamera = this.parent;
  90971. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  90972. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  90973. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  90974. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  90975. //babylon compatible matrix
  90976. if (!this.getScene().useRightHandedSystem) {
  90977. [8, 9, 10, 11].forEach(function (num) {
  90978. _this._projectionMatrix.m[num] *= -1;
  90979. });
  90980. }
  90981. return this._projectionMatrix;
  90982. };
  90983. /**
  90984. * Initializes the controllers and their meshes
  90985. */
  90986. WebVRFreeCamera.prototype.initControllers = function () {
  90987. var _this = this;
  90988. this.controllers = [];
  90989. var manager = this.getScene().gamepadManager;
  90990. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  90991. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90992. var webVrController = gamepad;
  90993. if (webVrController.defaultModel) {
  90994. webVrController.defaultModel.setEnabled(false);
  90995. }
  90996. if (webVrController.hand === "right") {
  90997. _this._rightController = null;
  90998. }
  90999. if (webVrController.hand === "left") {
  91000. _this._leftController = null;
  91001. }
  91002. var controllerIndex = _this.controllers.indexOf(webVrController);
  91003. if (controllerIndex !== -1) {
  91004. _this.controllers.splice(controllerIndex, 1);
  91005. }
  91006. }
  91007. });
  91008. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  91009. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91010. var webVrController_1 = gamepad;
  91011. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  91012. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  91013. if (_this.webVROptions.controllerMeshes) {
  91014. if (webVrController_1.defaultModel) {
  91015. webVrController_1.defaultModel.setEnabled(true);
  91016. }
  91017. else {
  91018. // Load the meshes
  91019. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  91020. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  91021. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  91022. if (_this.webVROptions.defaultLightingOnControllers) {
  91023. if (!_this._lightOnControllers) {
  91024. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  91025. }
  91026. var activateLightOnSubMeshes_1 = function (mesh, light) {
  91027. var children = mesh.getChildren();
  91028. if (children.length !== 0) {
  91029. children.forEach(function (mesh) {
  91030. light.includedOnlyMeshes.push(mesh);
  91031. activateLightOnSubMeshes_1(mesh, light);
  91032. });
  91033. }
  91034. };
  91035. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  91036. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  91037. }
  91038. });
  91039. }
  91040. }
  91041. webVrController_1.attachToPoseControlledCamera(_this);
  91042. // since this is async - sanity check. Is the controller already stored?
  91043. if (_this.controllers.indexOf(webVrController_1) === -1) {
  91044. //add to the controllers array
  91045. _this.controllers.push(webVrController_1);
  91046. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  91047. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  91048. // So we're overriding setting left & right manually to be sure
  91049. var firstViveWandDetected = false;
  91050. for (var i = 0; i < _this.controllers.length; i++) {
  91051. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91052. if (!firstViveWandDetected) {
  91053. firstViveWandDetected = true;
  91054. _this.controllers[i].hand = "left";
  91055. }
  91056. else {
  91057. _this.controllers[i].hand = "right";
  91058. }
  91059. }
  91060. }
  91061. //did we find enough controllers? Great! let the developer know.
  91062. if (_this.controllers.length >= 2) {
  91063. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  91064. }
  91065. }
  91066. }
  91067. });
  91068. };
  91069. return WebVRFreeCamera;
  91070. }(BABYLON.FreeCamera));
  91071. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  91072. })(BABYLON || (BABYLON = {}));
  91073. //# sourceMappingURL=babylon.webVRCamera.js.map
  91074. var BABYLON;
  91075. (function (BABYLON) {
  91076. // We're mainly based on the logic defined into the FreeCamera code
  91077. /**
  91078. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  91079. * being tilted forward or back and left or right.
  91080. */
  91081. var DeviceOrientationCamera = /** @class */ (function (_super) {
  91082. __extends(DeviceOrientationCamera, _super);
  91083. /**
  91084. * Creates a new device orientation camera
  91085. * @param name The name of the camera
  91086. * @param position The start position camera
  91087. * @param scene The scene the camera belongs to
  91088. */
  91089. function DeviceOrientationCamera(name, position, scene) {
  91090. var _this = _super.call(this, name, position, scene) || this;
  91091. _this._quaternionCache = new BABYLON.Quaternion();
  91092. _this.inputs.addDeviceOrientation();
  91093. return _this;
  91094. }
  91095. /**
  91096. * Gets the current instance class name ("DeviceOrientationCamera").
  91097. * This helps avoiding instanceof at run time.
  91098. * @returns the class name
  91099. */
  91100. DeviceOrientationCamera.prototype.getClassName = function () {
  91101. return "DeviceOrientationCamera";
  91102. };
  91103. /**
  91104. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  91105. */
  91106. DeviceOrientationCamera.prototype._checkInputs = function () {
  91107. _super.prototype._checkInputs.call(this);
  91108. this._quaternionCache.copyFrom(this.rotationQuaternion);
  91109. if (this._initialQuaternion) {
  91110. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91111. }
  91112. };
  91113. /**
  91114. * Reset the camera to its default orientation on the specified axis only.
  91115. * @param axis The axis to reset
  91116. */
  91117. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  91118. var _this = this;
  91119. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  91120. //can only work if this camera has a rotation quaternion already.
  91121. if (!this.rotationQuaternion)
  91122. return;
  91123. if (!this._initialQuaternion) {
  91124. this._initialQuaternion = new BABYLON.Quaternion();
  91125. }
  91126. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  91127. ['x', 'y', 'z'].forEach(function (axisName) {
  91128. if (!axis[axisName]) {
  91129. _this._initialQuaternion[axisName] = 0;
  91130. }
  91131. else {
  91132. _this._initialQuaternion[axisName] *= -1;
  91133. }
  91134. });
  91135. this._initialQuaternion.normalize();
  91136. //force rotation update
  91137. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91138. };
  91139. return DeviceOrientationCamera;
  91140. }(BABYLON.FreeCamera));
  91141. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  91142. })(BABYLON || (BABYLON = {}));
  91143. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  91144. var BABYLON;
  91145. (function (BABYLON) {
  91146. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  91147. __extends(VRDeviceOrientationFreeCamera, _super);
  91148. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91149. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91150. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91151. var _this = _super.call(this, name, position, scene) || this;
  91152. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91153. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91154. return _this;
  91155. }
  91156. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  91157. return "VRDeviceOrientationFreeCamera";
  91158. };
  91159. return VRDeviceOrientationFreeCamera;
  91160. }(BABYLON.DeviceOrientationCamera));
  91161. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  91162. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  91163. __extends(VRDeviceOrientationGamepadCamera, _super);
  91164. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91165. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91166. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91167. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  91168. _this.inputs.addGamepad();
  91169. return _this;
  91170. }
  91171. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  91172. return "VRDeviceOrientationGamepadCamera";
  91173. };
  91174. return VRDeviceOrientationGamepadCamera;
  91175. }(VRDeviceOrientationFreeCamera));
  91176. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  91177. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  91178. __extends(VRDeviceOrientationArcRotateCamera, _super);
  91179. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  91180. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91181. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91182. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91183. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91184. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91185. _this.inputs.addVRDeviceOrientation();
  91186. return _this;
  91187. }
  91188. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  91189. return "VRDeviceOrientationArcRotateCamera";
  91190. };
  91191. return VRDeviceOrientationArcRotateCamera;
  91192. }(BABYLON.ArcRotateCamera));
  91193. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  91194. })(BABYLON || (BABYLON = {}));
  91195. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  91196. var BABYLON;
  91197. (function (BABYLON) {
  91198. /**
  91199. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91200. */
  91201. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91202. __extends(AnaglyphFreeCamera, _super);
  91203. /**
  91204. * Creates a new AnaglyphFreeCamera
  91205. * @param name defines camera name
  91206. * @param position defines initial position
  91207. * @param interaxialDistance defines distance between each color axis
  91208. * @param scene defines the hosting scene
  91209. */
  91210. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91211. var _this = _super.call(this, name, position, scene) || this;
  91212. _this.interaxialDistance = interaxialDistance;
  91213. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91214. return _this;
  91215. }
  91216. /**
  91217. * Gets camera class name
  91218. * @returns AnaglyphFreeCamera
  91219. */
  91220. AnaglyphFreeCamera.prototype.getClassName = function () {
  91221. return "AnaglyphFreeCamera";
  91222. };
  91223. return AnaglyphFreeCamera;
  91224. }(BABYLON.FreeCamera));
  91225. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91226. /**
  91227. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91228. */
  91229. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91230. __extends(AnaglyphArcRotateCamera, _super);
  91231. /**
  91232. * Creates a new AnaglyphArcRotateCamera
  91233. * @param name defines camera name
  91234. * @param alpha defines alpha angle (in radians)
  91235. * @param beta defines beta angle (in radians)
  91236. * @param radius defines radius
  91237. * @param target defines camera target
  91238. * @param interaxialDistance defines distance between each color axis
  91239. * @param scene defines the hosting scene
  91240. */
  91241. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91242. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91243. _this.interaxialDistance = interaxialDistance;
  91244. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91245. return _this;
  91246. }
  91247. /**
  91248. * Gets camera class name
  91249. * @returns AnaglyphArcRotateCamera
  91250. */
  91251. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91252. return "AnaglyphArcRotateCamera";
  91253. };
  91254. return AnaglyphArcRotateCamera;
  91255. }(BABYLON.ArcRotateCamera));
  91256. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91257. /**
  91258. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91259. */
  91260. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91261. __extends(AnaglyphGamepadCamera, _super);
  91262. /**
  91263. * Creates a new AnaglyphGamepadCamera
  91264. * @param name defines camera name
  91265. * @param position defines initial position
  91266. * @param interaxialDistance defines distance between each color axis
  91267. * @param scene defines the hosting scene
  91268. */
  91269. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91270. var _this = _super.call(this, name, position, scene) || this;
  91271. _this.interaxialDistance = interaxialDistance;
  91272. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91273. return _this;
  91274. }
  91275. /**
  91276. * Gets camera class name
  91277. * @returns AnaglyphGamepadCamera
  91278. */
  91279. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91280. return "AnaglyphGamepadCamera";
  91281. };
  91282. return AnaglyphGamepadCamera;
  91283. }(BABYLON.GamepadCamera));
  91284. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91285. /**
  91286. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91287. */
  91288. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91289. __extends(AnaglyphUniversalCamera, _super);
  91290. /**
  91291. * Creates a new AnaglyphUniversalCamera
  91292. * @param name defines camera name
  91293. * @param position defines initial position
  91294. * @param interaxialDistance defines distance between each color axis
  91295. * @param scene defines the hosting scene
  91296. */
  91297. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91298. var _this = _super.call(this, name, position, scene) || this;
  91299. _this.interaxialDistance = interaxialDistance;
  91300. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91301. return _this;
  91302. }
  91303. /**
  91304. * Gets camera class name
  91305. * @returns AnaglyphUniversalCamera
  91306. */
  91307. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91308. return "AnaglyphUniversalCamera";
  91309. };
  91310. return AnaglyphUniversalCamera;
  91311. }(BABYLON.UniversalCamera));
  91312. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91313. /**
  91314. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91315. */
  91316. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91317. __extends(StereoscopicFreeCamera, _super);
  91318. /**
  91319. * Creates a new StereoscopicFreeCamera
  91320. * @param name defines camera name
  91321. * @param position defines initial position
  91322. * @param interaxialDistance defines distance between each color axis
  91323. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91324. * @param scene defines the hosting scene
  91325. */
  91326. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91327. var _this = _super.call(this, name, position, scene) || this;
  91328. _this.interaxialDistance = interaxialDistance;
  91329. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91330. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91331. return _this;
  91332. }
  91333. /**
  91334. * Gets camera class name
  91335. * @returns StereoscopicFreeCamera
  91336. */
  91337. StereoscopicFreeCamera.prototype.getClassName = function () {
  91338. return "StereoscopicFreeCamera";
  91339. };
  91340. return StereoscopicFreeCamera;
  91341. }(BABYLON.FreeCamera));
  91342. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91343. /**
  91344. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91345. */
  91346. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91347. __extends(StereoscopicArcRotateCamera, _super);
  91348. /**
  91349. * Creates a new StereoscopicArcRotateCamera
  91350. * @param name defines camera name
  91351. * @param alpha defines alpha angle (in radians)
  91352. * @param beta defines beta angle (in radians)
  91353. * @param radius defines radius
  91354. * @param target defines camera target
  91355. * @param interaxialDistance defines distance between each color axis
  91356. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91357. * @param scene defines the hosting scene
  91358. */
  91359. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91360. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91361. _this.interaxialDistance = interaxialDistance;
  91362. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91363. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91364. return _this;
  91365. }
  91366. /**
  91367. * Gets camera class name
  91368. * @returns StereoscopicArcRotateCamera
  91369. */
  91370. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91371. return "StereoscopicArcRotateCamera";
  91372. };
  91373. return StereoscopicArcRotateCamera;
  91374. }(BABYLON.ArcRotateCamera));
  91375. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91376. /**
  91377. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91378. */
  91379. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91380. __extends(StereoscopicGamepadCamera, _super);
  91381. /**
  91382. * Creates a new StereoscopicGamepadCamera
  91383. * @param name defines camera name
  91384. * @param position defines initial position
  91385. * @param interaxialDistance defines distance between each color axis
  91386. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91387. * @param scene defines the hosting scene
  91388. */
  91389. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91390. var _this = _super.call(this, name, position, scene) || this;
  91391. _this.interaxialDistance = interaxialDistance;
  91392. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91393. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91394. return _this;
  91395. }
  91396. /**
  91397. * Gets camera class name
  91398. * @returns StereoscopicGamepadCamera
  91399. */
  91400. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91401. return "StereoscopicGamepadCamera";
  91402. };
  91403. return StereoscopicGamepadCamera;
  91404. }(BABYLON.GamepadCamera));
  91405. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91406. /**
  91407. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91408. */
  91409. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91410. __extends(StereoscopicUniversalCamera, _super);
  91411. /**
  91412. * Creates a new StereoscopicUniversalCamera
  91413. * @param name defines camera name
  91414. * @param position defines initial position
  91415. * @param interaxialDistance defines distance between each color axis
  91416. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91417. * @param scene defines the hosting scene
  91418. */
  91419. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91420. var _this = _super.call(this, name, position, scene) || this;
  91421. _this.interaxialDistance = interaxialDistance;
  91422. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91423. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91424. return _this;
  91425. }
  91426. /**
  91427. * Gets camera class name
  91428. * @returns StereoscopicUniversalCamera
  91429. */
  91430. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91431. return "StereoscopicUniversalCamera";
  91432. };
  91433. return StereoscopicUniversalCamera;
  91434. }(BABYLON.UniversalCamera));
  91435. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91436. })(BABYLON || (BABYLON = {}));
  91437. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  91438. var BABYLON;
  91439. (function (BABYLON) {
  91440. var VRExperienceHelperGazer = /** @class */ (function () {
  91441. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  91442. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  91443. this.scene = scene;
  91444. this._pointerDownOnMeshAsked = false;
  91445. this._isActionableMesh = false;
  91446. this._teleportationRequestInitiated = false;
  91447. this._teleportationBackRequestInitiated = false;
  91448. this._rotationRightAsked = false;
  91449. this._rotationLeftAsked = false;
  91450. this._dpadPressed = true;
  91451. this._activePointer = false;
  91452. this._id = VRExperienceHelperGazer._idCounter++;
  91453. // Gaze tracker
  91454. if (!gazeTrackerToClone) {
  91455. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  91456. this._gazeTracker.bakeCurrentTransformIntoVertices();
  91457. this._gazeTracker.isPickable = false;
  91458. this._gazeTracker.isVisible = false;
  91459. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  91460. targetMat.specularColor = BABYLON.Color3.Black();
  91461. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91462. targetMat.backFaceCulling = false;
  91463. this._gazeTracker.material = targetMat;
  91464. }
  91465. else {
  91466. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  91467. }
  91468. }
  91469. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  91470. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  91471. };
  91472. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  91473. this._pointerDownOnMeshAsked = true;
  91474. if (this._currentHit) {
  91475. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  91476. }
  91477. };
  91478. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  91479. if (this._currentHit) {
  91480. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  91481. }
  91482. this._pointerDownOnMeshAsked = false;
  91483. };
  91484. VRExperienceHelperGazer.prototype._activatePointer = function () {
  91485. this._activePointer = true;
  91486. };
  91487. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  91488. this._activePointer = false;
  91489. };
  91490. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  91491. if (distance === void 0) { distance = 100; }
  91492. };
  91493. VRExperienceHelperGazer.prototype.dispose = function () {
  91494. this._interactionsEnabled = false;
  91495. this._teleportationEnabled = false;
  91496. if (this._gazeTracker) {
  91497. this._gazeTracker.dispose();
  91498. }
  91499. };
  91500. VRExperienceHelperGazer._idCounter = 0;
  91501. return VRExperienceHelperGazer;
  91502. }());
  91503. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  91504. __extends(VRExperienceHelperControllerGazer, _super);
  91505. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  91506. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  91507. _this.webVRController = webVRController;
  91508. // Laser pointer
  91509. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  91510. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  91511. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91512. laserPointerMaterial.alpha = 0.6;
  91513. _this._laserPointer.material = laserPointerMaterial;
  91514. _this._laserPointer.rotation.x = Math.PI / 2;
  91515. _this._laserPointer.position.z = -0.5;
  91516. _this._laserPointer.isVisible = false;
  91517. _this._laserPointer.isPickable = false;
  91518. if (!webVRController.mesh) {
  91519. // Create an empty mesh that is used prior to loading the high quality model
  91520. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  91521. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  91522. preloadPointerPose.rotation.x = -0.7;
  91523. preloadMesh.addChild(preloadPointerPose);
  91524. webVRController.attachToMesh(preloadMesh);
  91525. }
  91526. _this._setLaserPointerParent(webVRController.mesh);
  91527. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  91528. _this._setLaserPointerParent(mesh);
  91529. });
  91530. return _this;
  91531. }
  91532. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  91533. return this.webVRController.getForwardRay(length);
  91534. };
  91535. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  91536. _super.prototype._activatePointer.call(this);
  91537. this._laserPointer.isVisible = true;
  91538. };
  91539. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  91540. _super.prototype._deactivatePointer.call(this);
  91541. this._laserPointer.isVisible = false;
  91542. };
  91543. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  91544. this._laserPointer.material.emissiveColor = color;
  91545. };
  91546. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  91547. var makeNotPick = function (root) {
  91548. root.name += " laserPointer";
  91549. root.isPickable = false;
  91550. root.getChildMeshes().forEach(function (c) {
  91551. makeNotPick(c);
  91552. });
  91553. };
  91554. makeNotPick(mesh);
  91555. var childMeshes = mesh.getChildMeshes();
  91556. this.webVRController._pointingPoseNode = null;
  91557. for (var i = 0; i < childMeshes.length; i++) {
  91558. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  91559. mesh = childMeshes[i];
  91560. this.webVRController._pointingPoseNode = mesh;
  91561. break;
  91562. }
  91563. }
  91564. this._laserPointer.parent = mesh;
  91565. };
  91566. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  91567. if (distance === void 0) { distance = 100; }
  91568. this._laserPointer.scaling.y = distance;
  91569. this._laserPointer.position.z = -distance / 2;
  91570. };
  91571. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  91572. _super.prototype.dispose.call(this);
  91573. this._laserPointer.dispose();
  91574. if (this._meshAttachedObserver) {
  91575. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  91576. }
  91577. };
  91578. return VRExperienceHelperControllerGazer;
  91579. }(VRExperienceHelperGazer));
  91580. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  91581. __extends(VRExperienceHelperCameraGazer, _super);
  91582. function VRExperienceHelperCameraGazer(getCamera, scene) {
  91583. var _this = _super.call(this, scene) || this;
  91584. _this.getCamera = getCamera;
  91585. return _this;
  91586. }
  91587. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  91588. var camera = this.getCamera();
  91589. if (camera) {
  91590. return camera.getForwardRay(length);
  91591. }
  91592. else {
  91593. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  91594. }
  91595. };
  91596. return VRExperienceHelperCameraGazer;
  91597. }(VRExperienceHelperGazer));
  91598. /**
  91599. * Helps to quickly add VR support to an existing scene.
  91600. * See http://doc.babylonjs.com/how_to/webvr_helper
  91601. */
  91602. var VRExperienceHelper = /** @class */ (function () {
  91603. /**
  91604. * Instantiates a VRExperienceHelper.
  91605. * Helps to quickly add VR support to an existing scene.
  91606. * @param scene The scene the VRExperienceHelper belongs to.
  91607. * @param webVROptions Options to modify the vr experience helper's behavior.
  91608. */
  91609. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  91610. if (webVROptions === void 0) { webVROptions = {}; }
  91611. var _this = this;
  91612. this.webVROptions = webVROptions;
  91613. // Can the system support WebVR, even if a headset isn't plugged in?
  91614. this._webVRsupported = false;
  91615. // If WebVR is supported, is a headset plugged in and are we ready to present?
  91616. this._webVRready = false;
  91617. // Are we waiting for the requestPresent callback to complete?
  91618. this._webVRrequesting = false;
  91619. // Are we presenting to the headset right now?
  91620. this._webVRpresenting = false;
  91621. // Are we presenting in the fullscreen fallback?
  91622. this._fullscreenVRpresenting = false;
  91623. /**
  91624. * Observable raised when entering VR.
  91625. */
  91626. this.onEnteringVRObservable = new BABYLON.Observable();
  91627. /**
  91628. * Observable raised when exiting VR.
  91629. */
  91630. this.onExitingVRObservable = new BABYLON.Observable();
  91631. /**
  91632. * Observable raised when controller mesh is loaded.
  91633. */
  91634. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91635. this._useCustomVRButton = false;
  91636. this._teleportationRequested = false;
  91637. this._teleportActive = false;
  91638. this._floorMeshesCollection = [];
  91639. this._rotationAllowed = true;
  91640. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  91641. this._isDefaultTeleportationTarget = true;
  91642. this._teleportationFillColor = "#444444";
  91643. this._teleportationBorderColor = "#FFFFFF";
  91644. this._rotationAngle = 0;
  91645. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  91646. this._padSensibilityUp = 0.65;
  91647. this._padSensibilityDown = 0.35;
  91648. this.leftController = null;
  91649. this.rightController = null;
  91650. /**
  91651. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  91652. */
  91653. this.onNewMeshSelected = new BABYLON.Observable();
  91654. /**
  91655. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  91656. */
  91657. this.onNewMeshPicked = new BABYLON.Observable();
  91658. /**
  91659. * Observable raised before camera teleportation
  91660. */
  91661. this.onBeforeCameraTeleport = new BABYLON.Observable();
  91662. /**
  91663. * Observable raised after camera teleportation
  91664. */
  91665. this.onAfterCameraTeleport = new BABYLON.Observable();
  91666. /**
  91667. * Observable raised when current selected mesh gets unselected
  91668. */
  91669. this.onSelectedMeshUnselected = new BABYLON.Observable();
  91670. /**
  91671. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  91672. */
  91673. this.teleportationEnabled = true;
  91674. this._teleportationInitialized = false;
  91675. this._interactionsEnabled = false;
  91676. this._interactionsRequested = false;
  91677. this._displayGaze = true;
  91678. this._displayLaserPointer = true;
  91679. this._onResize = function () {
  91680. _this.moveButtonToBottomRight();
  91681. if (_this._fullscreenVRpresenting && _this._webVRready) {
  91682. _this.exitVR();
  91683. }
  91684. };
  91685. this._onFullscreenChange = function () {
  91686. if (document.fullscreen !== undefined) {
  91687. _this._fullscreenVRpresenting = document.fullscreen;
  91688. }
  91689. else if (document.mozFullScreen !== undefined) {
  91690. _this._fullscreenVRpresenting = document.mozFullScreen;
  91691. }
  91692. else if (document.webkitIsFullScreen !== undefined) {
  91693. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  91694. }
  91695. else if (document.msIsFullScreen !== undefined) {
  91696. _this._fullscreenVRpresenting = document.msIsFullScreen;
  91697. }
  91698. else if (document.msFullscreenElement !== undefined) {
  91699. _this._fullscreenVRpresenting = document.msFullscreenElement;
  91700. }
  91701. if (!_this._fullscreenVRpresenting && _this._canvas) {
  91702. _this.exitVR();
  91703. if (!_this._useCustomVRButton) {
  91704. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  91705. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  91706. }
  91707. }
  91708. };
  91709. this.beforeRender = function () {
  91710. if (_this.leftController && _this.leftController._activePointer) {
  91711. _this._castRayAndSelectObject(_this.leftController);
  91712. }
  91713. if (_this.rightController && _this.rightController._activePointer) {
  91714. _this._castRayAndSelectObject(_this.rightController);
  91715. }
  91716. if (_this._noControllerIsActive) {
  91717. _this._castRayAndSelectObject(_this._cameraGazer);
  91718. }
  91719. else {
  91720. _this._cameraGazer._gazeTracker.isVisible = false;
  91721. }
  91722. };
  91723. this._onNewGamepadConnected = function (gamepad) {
  91724. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  91725. if (gamepad.leftStick) {
  91726. gamepad.onleftstickchanged(function (stickValues) {
  91727. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  91728. // Listening to classic/xbox gamepad only if no VR controller is active
  91729. if ((!_this.leftController && !_this.rightController) ||
  91730. ((_this.leftController && !_this.leftController._activePointer) &&
  91731. (_this.rightController && !_this.rightController._activePointer))) {
  91732. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  91733. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  91734. }
  91735. }
  91736. });
  91737. }
  91738. if (gamepad.rightStick) {
  91739. gamepad.onrightstickchanged(function (stickValues) {
  91740. if (_this._teleportationInitialized) {
  91741. _this._checkRotate(stickValues, _this._cameraGazer);
  91742. }
  91743. });
  91744. }
  91745. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  91746. gamepad.onbuttondown(function (buttonPressed) {
  91747. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91748. _this._cameraGazer._selectionPointerDown();
  91749. }
  91750. });
  91751. gamepad.onbuttonup(function (buttonPressed) {
  91752. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91753. _this._cameraGazer._selectionPointerUp();
  91754. }
  91755. });
  91756. }
  91757. }
  91758. else {
  91759. var webVRController = gamepad;
  91760. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  91761. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  91762. _this.rightController = controller;
  91763. }
  91764. else {
  91765. _this.leftController = controller;
  91766. }
  91767. _this._tryEnableInteractionOnController(controller);
  91768. }
  91769. };
  91770. // 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
  91771. this._tryEnableInteractionOnController = function (controller) {
  91772. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  91773. _this._enableInteractionOnController(controller);
  91774. }
  91775. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  91776. _this._enableTeleportationOnController(controller);
  91777. }
  91778. };
  91779. this._onNewGamepadDisconnected = function (gamepad) {
  91780. if (gamepad instanceof BABYLON.WebVRController) {
  91781. if (gamepad.hand === "left" && _this.leftController != null) {
  91782. _this.leftController.dispose();
  91783. _this.leftController = null;
  91784. }
  91785. if (gamepad.hand === "right" && _this.rightController != null) {
  91786. _this.rightController.dispose();
  91787. _this.rightController = null;
  91788. }
  91789. }
  91790. };
  91791. this._workingVector = BABYLON.Vector3.Zero();
  91792. this._workingQuaternion = BABYLON.Quaternion.Identity();
  91793. this._workingMatrix = BABYLON.Matrix.Identity();
  91794. this._scene = scene;
  91795. this._canvas = scene.getEngine().getRenderingCanvas();
  91796. // Parse options
  91797. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  91798. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  91799. }
  91800. if (webVROptions.createDeviceOrientationCamera === undefined) {
  91801. webVROptions.createDeviceOrientationCamera = true;
  91802. }
  91803. if (webVROptions.laserToggle === undefined) {
  91804. webVROptions.laserToggle = true;
  91805. }
  91806. if (webVROptions.defaultHeight === undefined) {
  91807. webVROptions.defaultHeight = 1.7;
  91808. }
  91809. if (webVROptions.useCustomVRButton) {
  91810. this._useCustomVRButton = true;
  91811. if (webVROptions.customVRButton) {
  91812. this._btnVR = webVROptions.customVRButton;
  91813. }
  91814. }
  91815. if (webVROptions.rayLength) {
  91816. this._rayLength = webVROptions.rayLength;
  91817. }
  91818. this._defaultHeight = webVROptions.defaultHeight;
  91819. if (webVROptions.positionScale) {
  91820. this._rayLength *= webVROptions.positionScale;
  91821. this._defaultHeight *= webVROptions.positionScale;
  91822. }
  91823. // Set position
  91824. if (this._scene.activeCamera) {
  91825. this._position = this._scene.activeCamera.position.clone();
  91826. }
  91827. else {
  91828. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  91829. }
  91830. // Set non-vr camera
  91831. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  91832. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  91833. // Copy data from existing camera
  91834. if (this._scene.activeCamera) {
  91835. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91836. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  91837. // Set rotation from previous camera
  91838. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  91839. var targetCamera = this._scene.activeCamera;
  91840. if (targetCamera.rotationQuaternion) {
  91841. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  91842. }
  91843. else {
  91844. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  91845. }
  91846. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  91847. }
  91848. }
  91849. this._scene.activeCamera = this._deviceOrientationCamera;
  91850. if (this._canvas) {
  91851. this._scene.activeCamera.attachControl(this._canvas);
  91852. }
  91853. }
  91854. else {
  91855. this._existingCamera = this._scene.activeCamera;
  91856. }
  91857. // Create VR cameras
  91858. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91859. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  91860. }
  91861. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  91862. this._webVRCamera.useStandingMatrix();
  91863. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  91864. // Create default button
  91865. if (!this._useCustomVRButton) {
  91866. this._btnVR = document.createElement("BUTTON");
  91867. this._btnVR.className = "babylonVRicon";
  91868. this._btnVR.id = "babylonVRiconbtn";
  91869. this._btnVR.title = "Click to switch to VR";
  91870. 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) }";
  91871. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  91872. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  91873. // css += ".babylonVRicon.vrdisplaysupported { }";
  91874. // css += ".babylonVRicon.vrdisplayready { }";
  91875. // css += ".babylonVRicon.vrdisplayrequesting { }";
  91876. var style = document.createElement('style');
  91877. style.appendChild(document.createTextNode(css));
  91878. document.getElementsByTagName('head')[0].appendChild(style);
  91879. this.moveButtonToBottomRight();
  91880. }
  91881. // VR button click event
  91882. if (this._btnVR) {
  91883. this._btnVR.addEventListener("click", function () {
  91884. if (!_this.isInVRMode) {
  91885. _this.enterVR();
  91886. }
  91887. else {
  91888. _this.exitVR();
  91889. }
  91890. });
  91891. }
  91892. // Window events
  91893. window.addEventListener("resize", this._onResize);
  91894. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  91895. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  91896. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  91897. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  91898. document.onmsfullscreenchange = this._onFullscreenChange;
  91899. // Display vr button when headset is connected
  91900. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91901. this.displayVRButton();
  91902. }
  91903. else {
  91904. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  91905. if (e.vrDisplay) {
  91906. _this.displayVRButton();
  91907. }
  91908. });
  91909. }
  91910. // Exiting VR mode using 'ESC' key on desktop
  91911. this._onKeyDown = function (event) {
  91912. if (event.keyCode === 27 && _this.isInVRMode) {
  91913. _this.exitVR();
  91914. }
  91915. };
  91916. document.addEventListener("keydown", this._onKeyDown);
  91917. // Exiting VR mode double tapping the touch screen
  91918. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  91919. if (_this.isInVRMode) {
  91920. _this.exitVR();
  91921. if (_this._fullscreenVRpresenting) {
  91922. _this._scene.getEngine().switchFullscreen(true);
  91923. }
  91924. }
  91925. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  91926. // Listen for WebVR display changes
  91927. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  91928. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  91929. this._onVRRequestPresentStart = function () {
  91930. _this._webVRrequesting = true;
  91931. _this.updateButtonVisibility();
  91932. };
  91933. this._onVRRequestPresentComplete = function (success) {
  91934. _this._webVRrequesting = false;
  91935. _this.updateButtonVisibility();
  91936. };
  91937. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  91938. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  91939. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  91940. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91941. scene.onDisposeObservable.add(function () {
  91942. _this.dispose();
  91943. });
  91944. // Gamepad connection events
  91945. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  91946. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  91947. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  91948. this.updateButtonVisibility();
  91949. //create easing functions
  91950. this._circleEase = new BABYLON.CircleEase();
  91951. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91952. if (this.webVROptions.floorMeshes) {
  91953. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  91954. }
  91955. }
  91956. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  91957. /** Return this.onEnteringVRObservable
  91958. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  91959. */
  91960. get: function () {
  91961. return this.onEnteringVRObservable;
  91962. },
  91963. enumerable: true,
  91964. configurable: true
  91965. });
  91966. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  91967. /** Return this.onExitingVRObservable
  91968. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  91969. */
  91970. get: function () {
  91971. return this.onExitingVRObservable;
  91972. },
  91973. enumerable: true,
  91974. configurable: true
  91975. });
  91976. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  91977. /** Return this.onControllerMeshLoadedObservable
  91978. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  91979. */
  91980. get: function () {
  91981. return this.onControllerMeshLoadedObservable;
  91982. },
  91983. enumerable: true,
  91984. configurable: true
  91985. });
  91986. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  91987. /**
  91988. * The mesh used to display where the user is going to teleport.
  91989. */
  91990. get: function () {
  91991. return this._teleportationTarget;
  91992. },
  91993. /**
  91994. * Sets the mesh to be used to display where the user is going to teleport.
  91995. */
  91996. set: function (value) {
  91997. if (value) {
  91998. value.name = "teleportationTarget";
  91999. this._isDefaultTeleportationTarget = false;
  92000. this._teleportationTarget = value;
  92001. }
  92002. },
  92003. enumerable: true,
  92004. configurable: true
  92005. });
  92006. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92007. /**
  92008. * The mesh used to display where the user is selecting,
  92009. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92010. * See http://doc.babylonjs.com/resources/baking_transformations
  92011. */
  92012. get: function () {
  92013. return this._cameraGazer._gazeTracker;
  92014. },
  92015. set: function (value) {
  92016. if (value) {
  92017. this._cameraGazer._gazeTracker = value;
  92018. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92019. this._cameraGazer._gazeTracker.isPickable = false;
  92020. this._cameraGazer._gazeTracker.isVisible = false;
  92021. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92022. if (this.leftController) {
  92023. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92024. }
  92025. if (this.rightController) {
  92026. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92027. }
  92028. }
  92029. },
  92030. enumerable: true,
  92031. configurable: true
  92032. });
  92033. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92034. /**
  92035. * If the ray of the gaze should be displayed.
  92036. */
  92037. get: function () {
  92038. return this._displayGaze;
  92039. },
  92040. /**
  92041. * Sets if the ray of the gaze should be displayed.
  92042. */
  92043. set: function (value) {
  92044. this._displayGaze = value;
  92045. if (!value) {
  92046. this._cameraGazer._gazeTracker.isVisible = false;
  92047. if (this.leftController) {
  92048. this.leftController._gazeTracker.isVisible = false;
  92049. }
  92050. if (this.rightController) {
  92051. this.rightController._gazeTracker.isVisible = false;
  92052. }
  92053. }
  92054. },
  92055. enumerable: true,
  92056. configurable: true
  92057. });
  92058. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92059. /**
  92060. * If the ray of the LaserPointer should be displayed.
  92061. */
  92062. get: function () {
  92063. return this._displayLaserPointer;
  92064. },
  92065. /**
  92066. * Sets if the ray of the LaserPointer should be displayed.
  92067. */
  92068. set: function (value) {
  92069. this._displayLaserPointer = value;
  92070. if (!value) {
  92071. if (this.rightController) {
  92072. this.rightController._deactivatePointer();
  92073. this.rightController._gazeTracker.isVisible = false;
  92074. }
  92075. if (this.leftController) {
  92076. this.leftController._deactivatePointer();
  92077. this.leftController._gazeTracker.isVisible = false;
  92078. }
  92079. }
  92080. else {
  92081. if (this.rightController) {
  92082. this.rightController._activatePointer();
  92083. }
  92084. if (this.leftController) {
  92085. this.leftController._activatePointer();
  92086. }
  92087. }
  92088. },
  92089. enumerable: true,
  92090. configurable: true
  92091. });
  92092. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92093. /**
  92094. * The deviceOrientationCamera used as the camera when not in VR.
  92095. */
  92096. get: function () {
  92097. return this._deviceOrientationCamera;
  92098. },
  92099. enumerable: true,
  92100. configurable: true
  92101. });
  92102. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92103. /**
  92104. * Based on the current WebVR support, returns the current VR camera used.
  92105. */
  92106. get: function () {
  92107. if (this._webVRready) {
  92108. return this._webVRCamera;
  92109. }
  92110. else {
  92111. return this._scene.activeCamera;
  92112. }
  92113. },
  92114. enumerable: true,
  92115. configurable: true
  92116. });
  92117. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  92118. /**
  92119. * The webVRCamera which is used when in VR.
  92120. */
  92121. get: function () {
  92122. return this._webVRCamera;
  92123. },
  92124. enumerable: true,
  92125. configurable: true
  92126. });
  92127. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  92128. /**
  92129. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  92130. */
  92131. get: function () {
  92132. return this._vrDeviceOrientationCamera;
  92133. },
  92134. enumerable: true,
  92135. configurable: true
  92136. });
  92137. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  92138. get: function () {
  92139. var result = this._cameraGazer._teleportationRequestInitiated
  92140. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  92141. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  92142. return result;
  92143. },
  92144. enumerable: true,
  92145. configurable: true
  92146. });
  92147. // Raised when one of the controller has loaded successfully its associated default mesh
  92148. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  92149. if (this.leftController && this.leftController.webVRController == webVRController) {
  92150. if (webVRController.mesh) {
  92151. this.leftController._setLaserPointerParent(webVRController.mesh);
  92152. }
  92153. }
  92154. if (this.rightController && this.rightController.webVRController == webVRController) {
  92155. if (webVRController.mesh) {
  92156. this.rightController._setLaserPointerParent(webVRController.mesh);
  92157. }
  92158. }
  92159. try {
  92160. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  92161. }
  92162. catch (err) {
  92163. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  92164. }
  92165. };
  92166. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  92167. /**
  92168. * Gets a value indicating if we are currently in VR mode.
  92169. */
  92170. get: function () {
  92171. return this._webVRpresenting || this._fullscreenVRpresenting;
  92172. },
  92173. enumerable: true,
  92174. configurable: true
  92175. });
  92176. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  92177. var vrDisplay = this._scene.getEngine().getVRDevice();
  92178. if (vrDisplay) {
  92179. var wasPresenting = this._webVRpresenting;
  92180. // A VR display is connected
  92181. this._webVRpresenting = vrDisplay.isPresenting;
  92182. if (wasPresenting && !this._webVRpresenting)
  92183. this.exitVR();
  92184. }
  92185. else {
  92186. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  92187. }
  92188. this.updateButtonVisibility();
  92189. };
  92190. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  92191. this._webVRsupported = eventArgs.vrSupported;
  92192. this._webVRready = !!eventArgs.vrDisplay;
  92193. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  92194. this.updateButtonVisibility();
  92195. };
  92196. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  92197. if (this._canvas && !this._useCustomVRButton) {
  92198. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  92199. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  92200. }
  92201. };
  92202. VRExperienceHelper.prototype.displayVRButton = function () {
  92203. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  92204. document.body.appendChild(this._btnVR);
  92205. this._btnVRDisplayed = true;
  92206. }
  92207. };
  92208. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  92209. if (!this._btnVR || this._useCustomVRButton) {
  92210. return;
  92211. }
  92212. this._btnVR.className = "babylonVRicon";
  92213. if (this.isInVRMode) {
  92214. this._btnVR.className += " vrdisplaypresenting";
  92215. }
  92216. else {
  92217. if (this._webVRready)
  92218. this._btnVR.className += " vrdisplayready";
  92219. if (this._webVRsupported)
  92220. this._btnVR.className += " vrdisplaysupported";
  92221. if (this._webVRrequesting)
  92222. this._btnVR.className += " vrdisplayrequesting";
  92223. }
  92224. };
  92225. /**
  92226. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  92227. * Otherwise, will use the fullscreen API.
  92228. */
  92229. VRExperienceHelper.prototype.enterVR = function () {
  92230. if (this.onEnteringVRObservable) {
  92231. try {
  92232. this.onEnteringVRObservable.notifyObservers(this);
  92233. }
  92234. catch (err) {
  92235. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  92236. }
  92237. }
  92238. if (this._scene.activeCamera) {
  92239. this._position = this._scene.activeCamera.position.clone();
  92240. // make sure that we return to the last active camera
  92241. this._existingCamera = this._scene.activeCamera;
  92242. }
  92243. if (this._webVRrequesting)
  92244. return;
  92245. // If WebVR is supported and a headset is connected
  92246. if (this._webVRready) {
  92247. if (!this._webVRpresenting) {
  92248. this._webVRCamera.position = this._position;
  92249. this._scene.activeCamera = this._webVRCamera;
  92250. }
  92251. }
  92252. else if (this._vrDeviceOrientationCamera) {
  92253. this._vrDeviceOrientationCamera.position = this._position;
  92254. if (this._scene.activeCamera) {
  92255. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92256. }
  92257. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  92258. this._scene.getEngine().switchFullscreen(true);
  92259. this.updateButtonVisibility();
  92260. }
  92261. if (this._scene.activeCamera && this._canvas) {
  92262. this._scene.activeCamera.attachControl(this._canvas);
  92263. }
  92264. if (this._interactionsEnabled) {
  92265. this._scene.registerBeforeRender(this.beforeRender);
  92266. }
  92267. };
  92268. /**
  92269. * Attempt to exit VR, or fullscreen.
  92270. */
  92271. VRExperienceHelper.prototype.exitVR = function () {
  92272. if (this.onExitingVRObservable) {
  92273. try {
  92274. this.onExitingVRObservable.notifyObservers(this);
  92275. }
  92276. catch (err) {
  92277. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  92278. }
  92279. }
  92280. if (this._webVRpresenting) {
  92281. this._scene.getEngine().disableVR();
  92282. }
  92283. if (this._scene.activeCamera) {
  92284. this._position = this._scene.activeCamera.position.clone();
  92285. }
  92286. if (this._deviceOrientationCamera) {
  92287. this._deviceOrientationCamera.position = this._position;
  92288. this._scene.activeCamera = this._deviceOrientationCamera;
  92289. if (this._canvas) {
  92290. this._scene.activeCamera.attachControl(this._canvas);
  92291. }
  92292. }
  92293. else if (this._existingCamera) {
  92294. this._existingCamera.position = this._position;
  92295. this._scene.activeCamera = this._existingCamera;
  92296. }
  92297. this.updateButtonVisibility();
  92298. if (this._interactionsEnabled) {
  92299. this._scene.unregisterBeforeRender(this.beforeRender);
  92300. }
  92301. // resize to update width and height when exiting vr exits fullscreen
  92302. this._scene.getEngine().resize();
  92303. };
  92304. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  92305. /**
  92306. * The position of the vr experience helper.
  92307. */
  92308. get: function () {
  92309. return this._position;
  92310. },
  92311. /**
  92312. * Sets the position of the vr experience helper.
  92313. */
  92314. set: function (value) {
  92315. this._position = value;
  92316. if (this._scene.activeCamera) {
  92317. this._scene.activeCamera.position = value;
  92318. }
  92319. },
  92320. enumerable: true,
  92321. configurable: true
  92322. });
  92323. /**
  92324. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  92325. */
  92326. VRExperienceHelper.prototype.enableInteractions = function () {
  92327. var _this = this;
  92328. if (!this._interactionsEnabled) {
  92329. this._interactionsRequested = true;
  92330. if (this.leftController) {
  92331. this._enableInteractionOnController(this.leftController);
  92332. }
  92333. if (this.rightController) {
  92334. this._enableInteractionOnController(this.rightController);
  92335. }
  92336. this.raySelectionPredicate = function (mesh) {
  92337. return mesh.isVisible;
  92338. };
  92339. this.meshSelectionPredicate = function (mesh) {
  92340. return true;
  92341. };
  92342. this._raySelectionPredicate = function (mesh) {
  92343. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  92344. && mesh.name.indexOf("teleportationTarget") === -1
  92345. && mesh.name.indexOf("torusTeleportation") === -1
  92346. && mesh.name.indexOf("laserPointer") === -1)) {
  92347. return _this.raySelectionPredicate(mesh);
  92348. }
  92349. return false;
  92350. };
  92351. this._interactionsEnabled = true;
  92352. }
  92353. };
  92354. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  92355. get: function () {
  92356. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  92357. },
  92358. enumerable: true,
  92359. configurable: true
  92360. });
  92361. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  92362. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  92363. if (this._floorMeshesCollection[i].id === mesh.id) {
  92364. return true;
  92365. }
  92366. }
  92367. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  92368. return true;
  92369. }
  92370. return false;
  92371. };
  92372. /**
  92373. * Adds a floor mesh to be used for teleportation.
  92374. * @param floorMesh the mesh to be used for teleportation.
  92375. */
  92376. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  92377. if (!this._floorMeshesCollection) {
  92378. return;
  92379. }
  92380. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  92381. return;
  92382. }
  92383. this._floorMeshesCollection.push(floorMesh);
  92384. };
  92385. /**
  92386. * Removes a floor mesh from being used for teleportation.
  92387. * @param floorMesh the mesh to be removed.
  92388. */
  92389. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  92390. if (!this._floorMeshesCollection) {
  92391. return;
  92392. }
  92393. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  92394. if (meshIndex !== -1) {
  92395. this._floorMeshesCollection.splice(meshIndex, 1);
  92396. }
  92397. };
  92398. /**
  92399. * Enables interactions and teleportation using the VR controllers and gaze.
  92400. * @param vrTeleportationOptions options to modify teleportation behavior.
  92401. */
  92402. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  92403. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  92404. if (!this._teleportationInitialized) {
  92405. this._teleportationRequested = true;
  92406. this.enableInteractions();
  92407. if (vrTeleportationOptions.floorMeshName) {
  92408. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  92409. }
  92410. if (vrTeleportationOptions.floorMeshes) {
  92411. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  92412. }
  92413. if (this.leftController != null) {
  92414. this._enableTeleportationOnController(this.leftController);
  92415. }
  92416. if (this.rightController != null) {
  92417. this._enableTeleportationOnController(this.rightController);
  92418. }
  92419. // Creates an image processing post process for the vignette not relying
  92420. // on the main scene configuration for image processing to reduce setup and spaces
  92421. // (gamma/linear) conflicts.
  92422. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  92423. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  92424. imageProcessingConfiguration.vignetteEnabled = true;
  92425. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  92426. this._webVRCamera.detachPostProcess(this._postProcessMove);
  92427. this._teleportationInitialized = true;
  92428. if (this._isDefaultTeleportationTarget) {
  92429. this._createTeleportationCircles();
  92430. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  92431. }
  92432. }
  92433. };
  92434. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  92435. var _this = this;
  92436. var controllerMesh = controller.webVRController.mesh;
  92437. if (controllerMesh) {
  92438. controller._interactionsEnabled = true;
  92439. controller._activatePointer();
  92440. if (this.webVROptions.laserToggle) {
  92441. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  92442. // Enabling / disabling laserPointer
  92443. if (_this._displayLaserPointer && stateObject.value === 1) {
  92444. if (controller._activePointer) {
  92445. controller._deactivatePointer();
  92446. }
  92447. else {
  92448. controller._activatePointer();
  92449. }
  92450. if (_this.displayGaze) {
  92451. controller._gazeTracker.isVisible = controller._activePointer;
  92452. }
  92453. }
  92454. });
  92455. }
  92456. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  92457. var gazer = controller;
  92458. if (_this._noControllerIsActive) {
  92459. gazer = _this._cameraGazer;
  92460. }
  92461. if (!gazer._pointerDownOnMeshAsked) {
  92462. if (stateObject.value > _this._padSensibilityUp) {
  92463. gazer._selectionPointerDown();
  92464. }
  92465. }
  92466. else if (stateObject.value < _this._padSensibilityDown) {
  92467. gazer._selectionPointerUp();
  92468. }
  92469. });
  92470. }
  92471. };
  92472. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  92473. // Dont teleport if another gaze already requested teleportation
  92474. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  92475. return;
  92476. }
  92477. if (!gazer._teleportationRequestInitiated) {
  92478. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  92479. gazer._activatePointer();
  92480. gazer._teleportationRequestInitiated = true;
  92481. }
  92482. }
  92483. else {
  92484. // Listening to the proper controller values changes to confirm teleportation
  92485. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  92486. if (this._teleportActive) {
  92487. this._teleportCamera(this._haloCenter);
  92488. }
  92489. gazer._teleportationRequestInitiated = false;
  92490. }
  92491. }
  92492. };
  92493. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  92494. // Only rotate when user is not currently selecting a teleportation location
  92495. if (gazer._teleportationRequestInitiated) {
  92496. return;
  92497. }
  92498. if (!gazer._rotationLeftAsked) {
  92499. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  92500. gazer._rotationLeftAsked = true;
  92501. if (this._rotationAllowed) {
  92502. this._rotateCamera(false);
  92503. }
  92504. }
  92505. }
  92506. else {
  92507. if (stateObject.x > -this._padSensibilityDown) {
  92508. gazer._rotationLeftAsked = false;
  92509. }
  92510. }
  92511. if (!gazer._rotationRightAsked) {
  92512. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  92513. gazer._rotationRightAsked = true;
  92514. if (this._rotationAllowed) {
  92515. this._rotateCamera(true);
  92516. }
  92517. }
  92518. }
  92519. else {
  92520. if (stateObject.x < this._padSensibilityDown) {
  92521. gazer._rotationRightAsked = false;
  92522. }
  92523. }
  92524. };
  92525. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  92526. // Only teleport backwards when user is not currently selecting a teleportation location
  92527. if (gazer._teleportationRequestInitiated) {
  92528. return;
  92529. }
  92530. // Teleport backwards
  92531. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  92532. if (!gazer._teleportationBackRequestInitiated) {
  92533. if (!this.currentVRCamera) {
  92534. return;
  92535. }
  92536. // Get rotation and position of the current camera
  92537. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  92538. var position = this.currentVRCamera.position;
  92539. // If the camera has device position, use that instead
  92540. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  92541. rotation = this.currentVRCamera.deviceRotationQuaternion;
  92542. position = this.currentVRCamera.devicePosition;
  92543. }
  92544. // Get matrix with only the y rotation of the device rotation
  92545. rotation.toEulerAnglesToRef(this._workingVector);
  92546. this._workingVector.z = 0;
  92547. this._workingVector.x = 0;
  92548. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  92549. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  92550. // Rotate backwards ray by device rotation to cast at the ground behind the user
  92551. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  92552. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  92553. var ray = new BABYLON.Ray(position, this._workingVector);
  92554. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92555. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  92556. this._teleportCamera(hit.pickedPoint);
  92557. }
  92558. gazer._teleportationBackRequestInitiated = true;
  92559. }
  92560. }
  92561. else {
  92562. gazer._teleportationBackRequestInitiated = false;
  92563. }
  92564. };
  92565. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  92566. var _this = this;
  92567. var controllerMesh = controller.webVRController.mesh;
  92568. if (controllerMesh) {
  92569. if (!controller._interactionsEnabled) {
  92570. this._enableInteractionOnController(controller);
  92571. }
  92572. controller._interactionsEnabled = true;
  92573. controller._teleportationEnabled = true;
  92574. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92575. controller._dpadPressed = false;
  92576. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  92577. controller._dpadPressed = stateObject.pressed;
  92578. if (!controller._dpadPressed) {
  92579. controller._rotationLeftAsked = false;
  92580. controller._rotationRightAsked = false;
  92581. controller._teleportationBackRequestInitiated = false;
  92582. }
  92583. });
  92584. }
  92585. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  92586. if (_this.teleportationEnabled) {
  92587. _this._checkTeleportBackwards(stateObject, controller);
  92588. _this._checkTeleportWithRay(stateObject, controller);
  92589. }
  92590. _this._checkRotate(stateObject, controller);
  92591. });
  92592. }
  92593. };
  92594. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  92595. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  92596. this._teleportationTarget.isPickable = false;
  92597. var length = 512;
  92598. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  92599. dynamicTexture.hasAlpha = true;
  92600. var context = dynamicTexture.getContext();
  92601. var centerX = length / 2;
  92602. var centerY = length / 2;
  92603. var radius = 200;
  92604. context.beginPath();
  92605. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  92606. context.fillStyle = this._teleportationFillColor;
  92607. context.fill();
  92608. context.lineWidth = 10;
  92609. context.strokeStyle = this._teleportationBorderColor;
  92610. context.stroke();
  92611. context.closePath();
  92612. dynamicTexture.update();
  92613. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  92614. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  92615. this._teleportationTarget.material = teleportationCircleMaterial;
  92616. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  92617. torus.isPickable = false;
  92618. torus.parent = this._teleportationTarget;
  92619. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92620. var keys = [];
  92621. keys.push({
  92622. frame: 0,
  92623. value: 0
  92624. });
  92625. keys.push({
  92626. frame: 30,
  92627. value: 0.4
  92628. });
  92629. keys.push({
  92630. frame: 60,
  92631. value: 0
  92632. });
  92633. animationInnerCircle.setKeys(keys);
  92634. var easingFunction = new BABYLON.SineEase();
  92635. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92636. animationInnerCircle.setEasingFunction(easingFunction);
  92637. torus.animations = [];
  92638. torus.animations.push(animationInnerCircle);
  92639. this._scene.beginAnimation(torus, 0, 60, true);
  92640. this._hideTeleportationTarget();
  92641. };
  92642. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  92643. this._teleportActive = true;
  92644. if (this._teleportationInitialized) {
  92645. this._teleportationTarget.isVisible = true;
  92646. if (this._isDefaultTeleportationTarget) {
  92647. this._teleportationTarget.getChildren()[0].isVisible = true;
  92648. }
  92649. }
  92650. };
  92651. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  92652. this._teleportActive = false;
  92653. if (this._teleportationInitialized) {
  92654. this._teleportationTarget.isVisible = false;
  92655. if (this._isDefaultTeleportationTarget) {
  92656. this._teleportationTarget.getChildren()[0].isVisible = false;
  92657. }
  92658. }
  92659. };
  92660. VRExperienceHelper.prototype._rotateCamera = function (right) {
  92661. var _this = this;
  92662. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92663. return;
  92664. }
  92665. if (right) {
  92666. this._rotationAngle++;
  92667. }
  92668. else {
  92669. this._rotationAngle--;
  92670. }
  92671. this.currentVRCamera.animations = [];
  92672. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  92673. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92674. var animationRotationKeys = [];
  92675. animationRotationKeys.push({
  92676. frame: 0,
  92677. value: this.currentVRCamera.rotationQuaternion
  92678. });
  92679. animationRotationKeys.push({
  92680. frame: 6,
  92681. value: target
  92682. });
  92683. animationRotation.setKeys(animationRotationKeys);
  92684. animationRotation.setEasingFunction(this._circleEase);
  92685. this.currentVRCamera.animations.push(animationRotation);
  92686. this._postProcessMove.animations = [];
  92687. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92688. var vignetteWeightKeys = [];
  92689. vignetteWeightKeys.push({
  92690. frame: 0,
  92691. value: 0
  92692. });
  92693. vignetteWeightKeys.push({
  92694. frame: 3,
  92695. value: 4
  92696. });
  92697. vignetteWeightKeys.push({
  92698. frame: 6,
  92699. value: 0
  92700. });
  92701. animationPP.setKeys(vignetteWeightKeys);
  92702. animationPP.setEasingFunction(this._circleEase);
  92703. this._postProcessMove.animations.push(animationPP);
  92704. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92705. var vignetteStretchKeys = [];
  92706. vignetteStretchKeys.push({
  92707. frame: 0,
  92708. value: 0
  92709. });
  92710. vignetteStretchKeys.push({
  92711. frame: 3,
  92712. value: 10
  92713. });
  92714. vignetteStretchKeys.push({
  92715. frame: 6,
  92716. value: 0
  92717. });
  92718. animationPP2.setKeys(vignetteStretchKeys);
  92719. animationPP2.setEasingFunction(this._circleEase);
  92720. this._postProcessMove.animations.push(animationPP2);
  92721. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92722. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92723. this._postProcessMove.samples = 4;
  92724. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92725. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  92726. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92727. });
  92728. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  92729. };
  92730. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  92731. if (hit.pickedPoint) {
  92732. if (gazer._teleportationRequestInitiated) {
  92733. this._displayTeleportationTarget();
  92734. this._haloCenter.copyFrom(hit.pickedPoint);
  92735. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  92736. }
  92737. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  92738. if (pickNormal) {
  92739. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92740. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92741. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  92742. }
  92743. this._teleportationTarget.position.y += 0.1;
  92744. }
  92745. };
  92746. VRExperienceHelper.prototype._teleportCamera = function (location) {
  92747. var _this = this;
  92748. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92749. return;
  92750. }
  92751. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  92752. // offset of the headset from the anchor.
  92753. if (this.webVRCamera.leftCamera) {
  92754. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  92755. this._workingVector.subtractInPlace(this.webVRCamera.position);
  92756. location.subtractToRef(this._workingVector, this._workingVector);
  92757. }
  92758. else {
  92759. this._workingVector.copyFrom(location);
  92760. }
  92761. // Add height to account for user's height offset
  92762. if (this.isInVRMode) {
  92763. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  92764. }
  92765. else {
  92766. this._workingVector.y += this._defaultHeight;
  92767. }
  92768. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  92769. // Create animation from the camera's position to the new location
  92770. this.currentVRCamera.animations = [];
  92771. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92772. var animationCameraTeleportationKeys = [{
  92773. frame: 0,
  92774. value: this.currentVRCamera.position
  92775. },
  92776. {
  92777. frame: 11,
  92778. value: this._workingVector
  92779. }
  92780. ];
  92781. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  92782. animationCameraTeleportation.setEasingFunction(this._circleEase);
  92783. this.currentVRCamera.animations.push(animationCameraTeleportation);
  92784. this._postProcessMove.animations = [];
  92785. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92786. var vignetteWeightKeys = [];
  92787. vignetteWeightKeys.push({
  92788. frame: 0,
  92789. value: 0
  92790. });
  92791. vignetteWeightKeys.push({
  92792. frame: 5,
  92793. value: 8
  92794. });
  92795. vignetteWeightKeys.push({
  92796. frame: 11,
  92797. value: 0
  92798. });
  92799. animationPP.setKeys(vignetteWeightKeys);
  92800. this._postProcessMove.animations.push(animationPP);
  92801. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92802. var vignetteStretchKeys = [];
  92803. vignetteStretchKeys.push({
  92804. frame: 0,
  92805. value: 0
  92806. });
  92807. vignetteStretchKeys.push({
  92808. frame: 5,
  92809. value: 10
  92810. });
  92811. vignetteStretchKeys.push({
  92812. frame: 11,
  92813. value: 0
  92814. });
  92815. animationPP2.setKeys(vignetteStretchKeys);
  92816. this._postProcessMove.animations.push(animationPP2);
  92817. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92818. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92819. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92820. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  92821. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92822. });
  92823. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  92824. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  92825. });
  92826. this._hideTeleportationTarget();
  92827. };
  92828. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  92829. if (normal) {
  92830. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  92831. if (angle < Math.PI / 2) {
  92832. normal.scaleInPlace(-1);
  92833. }
  92834. }
  92835. return normal;
  92836. };
  92837. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  92838. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92839. return;
  92840. }
  92841. var ray = gazer._getForwardRay(this._rayLength);
  92842. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92843. if (hit) {
  92844. // Populate the contrllers mesh that can be used for drag/drop
  92845. if (gazer._laserPointer) {
  92846. hit.originMesh = gazer._laserPointer.parent;
  92847. }
  92848. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  92849. }
  92850. gazer._currentHit = hit;
  92851. // Moving the gazeTracker on the mesh face targetted
  92852. if (hit && hit.pickedPoint) {
  92853. if (this._displayGaze) {
  92854. var multiplier = 1;
  92855. gazer._gazeTracker.isVisible = true;
  92856. if (gazer._isActionableMesh) {
  92857. multiplier = 3;
  92858. }
  92859. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  92860. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  92861. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  92862. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  92863. // To avoid z-fighting
  92864. var deltaFighting = 0.002;
  92865. if (pickNormal) {
  92866. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92867. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92868. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  92869. }
  92870. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  92871. if (gazer._gazeTracker.position.x < 0) {
  92872. gazer._gazeTracker.position.x += deltaFighting;
  92873. }
  92874. else {
  92875. gazer._gazeTracker.position.x -= deltaFighting;
  92876. }
  92877. if (gazer._gazeTracker.position.y < 0) {
  92878. gazer._gazeTracker.position.y += deltaFighting;
  92879. }
  92880. else {
  92881. gazer._gazeTracker.position.y -= deltaFighting;
  92882. }
  92883. if (gazer._gazeTracker.position.z < 0) {
  92884. gazer._gazeTracker.position.z += deltaFighting;
  92885. }
  92886. else {
  92887. gazer._gazeTracker.position.z -= deltaFighting;
  92888. }
  92889. }
  92890. // Changing the size of the laser pointer based on the distance from the targetted point
  92891. gazer._updatePointerDistance(hit.distance);
  92892. }
  92893. else {
  92894. gazer._updatePointerDistance();
  92895. gazer._gazeTracker.isVisible = false;
  92896. }
  92897. if (hit && hit.pickedMesh) {
  92898. // The object selected is the floor, we're in a teleportation scenario
  92899. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  92900. // Moving the teleportation area to this targetted point
  92901. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  92902. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  92903. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92904. }
  92905. gazer._currentMeshSelected = null;
  92906. if (gazer._teleportationRequestInitiated) {
  92907. this._moveTeleportationSelectorTo(hit, gazer, ray);
  92908. }
  92909. return;
  92910. }
  92911. // If not, we're in a selection scenario
  92912. //this._teleportationAllowed = false;
  92913. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  92914. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  92915. this.onNewMeshPicked.notifyObservers(hit);
  92916. gazer._currentMeshSelected = hit.pickedMesh;
  92917. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  92918. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  92919. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  92920. gazer._isActionableMesh = true;
  92921. }
  92922. else {
  92923. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92924. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92925. gazer._isActionableMesh = false;
  92926. }
  92927. try {
  92928. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  92929. }
  92930. catch (err) {
  92931. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  92932. }
  92933. }
  92934. else {
  92935. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92936. gazer._currentMeshSelected = null;
  92937. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92938. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92939. }
  92940. }
  92941. }
  92942. else {
  92943. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92944. gazer._currentMeshSelected = null;
  92945. //this._teleportationAllowed = false;
  92946. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92947. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92948. }
  92949. };
  92950. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  92951. if (mesh) {
  92952. this.onSelectedMeshUnselected.notifyObservers(mesh);
  92953. }
  92954. };
  92955. /**
  92956. * Sets the color of the laser ray from the vr controllers.
  92957. * @param color new color for the ray.
  92958. */
  92959. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  92960. if (this.leftController) {
  92961. this.leftController._setLaserPointerColor(color);
  92962. }
  92963. if (this.rightController) {
  92964. this.rightController._setLaserPointerColor(color);
  92965. }
  92966. };
  92967. /**
  92968. * Sets the color of the ray from the vr headsets gaze.
  92969. * @param color new color for the ray.
  92970. */
  92971. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  92972. if (!this._cameraGazer._gazeTracker.material) {
  92973. return;
  92974. }
  92975. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  92976. if (this.leftController) {
  92977. this.leftController._gazeTracker.material.emissiveColor = color;
  92978. }
  92979. if (this.rightController) {
  92980. this.rightController._gazeTracker.material.emissiveColor = color;
  92981. }
  92982. };
  92983. /**
  92984. * Exits VR and disposes of the vr experience helper
  92985. */
  92986. VRExperienceHelper.prototype.dispose = function () {
  92987. if (this.isInVRMode) {
  92988. this.exitVR();
  92989. }
  92990. if (this._postProcessMove) {
  92991. this._postProcessMove.dispose();
  92992. }
  92993. if (this._webVRCamera) {
  92994. this._webVRCamera.dispose();
  92995. }
  92996. if (this._vrDeviceOrientationCamera) {
  92997. this._vrDeviceOrientationCamera.dispose();
  92998. }
  92999. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93000. document.body.removeChild(this._btnVR);
  93001. }
  93002. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93003. this._deviceOrientationCamera.dispose();
  93004. }
  93005. if (this._cameraGazer) {
  93006. this._cameraGazer.dispose();
  93007. }
  93008. if (this.leftController) {
  93009. this.leftController.dispose();
  93010. }
  93011. if (this.rightController) {
  93012. this.rightController.dispose();
  93013. }
  93014. if (this._teleportationTarget) {
  93015. this._teleportationTarget.dispose();
  93016. }
  93017. this._floorMeshesCollection = [];
  93018. document.removeEventListener("keydown", this._onKeyDown);
  93019. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93020. window.removeEventListener("resize", this._onResize);
  93021. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93022. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93023. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93024. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93025. document.onmsfullscreenchange = null;
  93026. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93027. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93028. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93029. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93030. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93031. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93032. this._scene.unregisterBeforeRender(this.beforeRender);
  93033. };
  93034. /**
  93035. * Gets the name of the VRExperienceHelper class
  93036. * @returns "VRExperienceHelper"
  93037. */
  93038. VRExperienceHelper.prototype.getClassName = function () {
  93039. return "VRExperienceHelper";
  93040. };
  93041. return VRExperienceHelper;
  93042. }());
  93043. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93044. })(BABYLON || (BABYLON = {}));
  93045. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93046. // Mainly based on these 2 articles :
  93047. // 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
  93048. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93049. var BABYLON;
  93050. (function (BABYLON) {
  93051. /**
  93052. * Defines the potential axis of a Joystick
  93053. */
  93054. var JoystickAxis;
  93055. (function (JoystickAxis) {
  93056. /** X axis */
  93057. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93058. /** Y axis */
  93059. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93060. /** Z axis */
  93061. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93062. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93063. /**
  93064. * Class used to define virtual joystick (used in touch mode)
  93065. */
  93066. var VirtualJoystick = /** @class */ (function () {
  93067. /**
  93068. * Creates a new virtual joystick
  93069. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93070. */
  93071. function VirtualJoystick(leftJoystick) {
  93072. var _this = this;
  93073. if (leftJoystick) {
  93074. this._leftJoystick = true;
  93075. }
  93076. else {
  93077. this._leftJoystick = false;
  93078. }
  93079. VirtualJoystick._globalJoystickIndex++;
  93080. // By default left & right arrow keys are moving the X
  93081. // and up & down keys are moving the Y
  93082. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93083. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93084. this.reverseLeftRight = false;
  93085. this.reverseUpDown = false;
  93086. // collections of pointers
  93087. this._touches = new BABYLON.StringDictionary();
  93088. this.deltaPosition = BABYLON.Vector3.Zero();
  93089. this._joystickSensibility = 25;
  93090. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93091. this._onResize = function (evt) {
  93092. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93093. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93094. if (VirtualJoystick.vjCanvas) {
  93095. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93096. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93097. }
  93098. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93099. };
  93100. // injecting a canvas element on top of the canvas 3D game
  93101. if (!VirtualJoystick.vjCanvas) {
  93102. window.addEventListener("resize", this._onResize, false);
  93103. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93104. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93105. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93106. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93107. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93108. VirtualJoystick.vjCanvas.style.width = "100%";
  93109. VirtualJoystick.vjCanvas.style.height = "100%";
  93110. VirtualJoystick.vjCanvas.style.position = "absolute";
  93111. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  93112. VirtualJoystick.vjCanvas.style.top = "0px";
  93113. VirtualJoystick.vjCanvas.style.left = "0px";
  93114. VirtualJoystick.vjCanvas.style.zIndex = "5";
  93115. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  93116. // Support for jQuery PEP polyfill
  93117. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  93118. var context = VirtualJoystick.vjCanvas.getContext('2d');
  93119. if (!context) {
  93120. throw new Error("Unable to create canvas for virtual joystick");
  93121. }
  93122. VirtualJoystick.vjCanvasContext = context;
  93123. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  93124. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93125. document.body.appendChild(VirtualJoystick.vjCanvas);
  93126. }
  93127. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  93128. this.pressed = false;
  93129. // default joystick color
  93130. this._joystickColor = "cyan";
  93131. this._joystickPointerID = -1;
  93132. // current joystick position
  93133. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  93134. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  93135. // origin joystick position
  93136. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  93137. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  93138. this._onPointerDownHandlerRef = function (evt) {
  93139. _this._onPointerDown(evt);
  93140. };
  93141. this._onPointerMoveHandlerRef = function (evt) {
  93142. _this._onPointerMove(evt);
  93143. };
  93144. this._onPointerUpHandlerRef = function (evt) {
  93145. _this._onPointerUp(evt);
  93146. };
  93147. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  93148. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  93149. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  93150. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  93151. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  93152. evt.preventDefault(); // Disables system menu
  93153. }, false);
  93154. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93155. }
  93156. /**
  93157. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  93158. * @param newJoystickSensibility defines the new sensibility
  93159. */
  93160. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  93161. this._joystickSensibility = newJoystickSensibility;
  93162. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93163. };
  93164. VirtualJoystick.prototype._onPointerDown = function (e) {
  93165. var positionOnScreenCondition;
  93166. e.preventDefault();
  93167. if (this._leftJoystick === true) {
  93168. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  93169. }
  93170. else {
  93171. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  93172. }
  93173. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  93174. // First contact will be dedicated to the virtual joystick
  93175. this._joystickPointerID = e.pointerId;
  93176. this._joystickPointerStartPos.x = e.clientX;
  93177. this._joystickPointerStartPos.y = e.clientY;
  93178. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  93179. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  93180. this._deltaJoystickVector.x = 0;
  93181. this._deltaJoystickVector.y = 0;
  93182. this.pressed = true;
  93183. this._touches.add(e.pointerId.toString(), e);
  93184. }
  93185. else {
  93186. // You can only trigger the action buttons with a joystick declared
  93187. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  93188. this._action();
  93189. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  93190. }
  93191. }
  93192. };
  93193. VirtualJoystick.prototype._onPointerMove = function (e) {
  93194. // If the current pointer is the one associated to the joystick (first touch contact)
  93195. if (this._joystickPointerID == e.pointerId) {
  93196. this._joystickPointerPos.x = e.clientX;
  93197. this._joystickPointerPos.y = e.clientY;
  93198. this._deltaJoystickVector = this._joystickPointerPos.clone();
  93199. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  93200. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  93201. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  93202. switch (this._axisTargetedByLeftAndRight) {
  93203. case JoystickAxis.X:
  93204. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  93205. break;
  93206. case JoystickAxis.Y:
  93207. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  93208. break;
  93209. case JoystickAxis.Z:
  93210. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  93211. break;
  93212. }
  93213. var directionUpDown = this.reverseUpDown ? 1 : -1;
  93214. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  93215. switch (this._axisTargetedByUpAndDown) {
  93216. case JoystickAxis.X:
  93217. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  93218. break;
  93219. case JoystickAxis.Y:
  93220. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  93221. break;
  93222. case JoystickAxis.Z:
  93223. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  93224. break;
  93225. }
  93226. }
  93227. else {
  93228. var data = this._touches.get(e.pointerId.toString());
  93229. if (data) {
  93230. data.x = e.clientX;
  93231. data.y = e.clientY;
  93232. }
  93233. }
  93234. };
  93235. VirtualJoystick.prototype._onPointerUp = function (e) {
  93236. if (this._joystickPointerID == e.pointerId) {
  93237. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  93238. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  93239. this._joystickPointerID = -1;
  93240. this.pressed = false;
  93241. }
  93242. else {
  93243. var touch = this._touches.get(e.pointerId.toString());
  93244. if (touch) {
  93245. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93246. }
  93247. }
  93248. this._deltaJoystickVector.x = 0;
  93249. this._deltaJoystickVector.y = 0;
  93250. this._touches.remove(e.pointerId.toString());
  93251. };
  93252. /**
  93253. * Change the color of the virtual joystick
  93254. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  93255. */
  93256. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  93257. this._joystickColor = newColor;
  93258. };
  93259. /**
  93260. * Defines a callback to call when the joystick is touched
  93261. * @param action defines the callback
  93262. */
  93263. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  93264. this._action = action;
  93265. };
  93266. /**
  93267. * Defines which axis you'd like to control for left & right
  93268. * @param axis defines the axis to use
  93269. */
  93270. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  93271. switch (axis) {
  93272. case JoystickAxis.X:
  93273. case JoystickAxis.Y:
  93274. case JoystickAxis.Z:
  93275. this._axisTargetedByLeftAndRight = axis;
  93276. break;
  93277. default:
  93278. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93279. break;
  93280. }
  93281. };
  93282. /**
  93283. * Defines which axis you'd like to control for up & down
  93284. * @param axis defines the axis to use
  93285. */
  93286. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  93287. switch (axis) {
  93288. case JoystickAxis.X:
  93289. case JoystickAxis.Y:
  93290. case JoystickAxis.Z:
  93291. this._axisTargetedByUpAndDown = axis;
  93292. break;
  93293. default:
  93294. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93295. break;
  93296. }
  93297. };
  93298. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  93299. var _this = this;
  93300. if (this.pressed) {
  93301. this._touches.forEach(function (key, touch) {
  93302. if (touch.pointerId === _this._joystickPointerID) {
  93303. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  93304. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  93305. VirtualJoystick.vjCanvasContext.beginPath();
  93306. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93307. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93308. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  93309. VirtualJoystick.vjCanvasContext.stroke();
  93310. VirtualJoystick.vjCanvasContext.closePath();
  93311. VirtualJoystick.vjCanvasContext.beginPath();
  93312. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93313. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93314. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  93315. VirtualJoystick.vjCanvasContext.stroke();
  93316. VirtualJoystick.vjCanvasContext.closePath();
  93317. VirtualJoystick.vjCanvasContext.beginPath();
  93318. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93319. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  93320. VirtualJoystick.vjCanvasContext.stroke();
  93321. VirtualJoystick.vjCanvasContext.closePath();
  93322. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  93323. }
  93324. else {
  93325. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93326. VirtualJoystick.vjCanvasContext.beginPath();
  93327. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  93328. VirtualJoystick.vjCanvasContext.beginPath();
  93329. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  93330. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93331. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  93332. VirtualJoystick.vjCanvasContext.stroke();
  93333. VirtualJoystick.vjCanvasContext.closePath();
  93334. touch.prevX = touch.x;
  93335. touch.prevY = touch.y;
  93336. }
  93337. ;
  93338. });
  93339. }
  93340. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93341. };
  93342. /**
  93343. * Release internal HTML canvas
  93344. */
  93345. VirtualJoystick.prototype.releaseCanvas = function () {
  93346. if (VirtualJoystick.vjCanvas) {
  93347. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  93348. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  93349. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  93350. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  93351. window.removeEventListener("resize", this._onResize);
  93352. document.body.removeChild(VirtualJoystick.vjCanvas);
  93353. VirtualJoystick.vjCanvas = null;
  93354. }
  93355. };
  93356. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  93357. VirtualJoystick._globalJoystickIndex = 0;
  93358. return VirtualJoystick;
  93359. }());
  93360. BABYLON.VirtualJoystick = VirtualJoystick;
  93361. })(BABYLON || (BABYLON = {}));
  93362. //# sourceMappingURL=babylon.virtualJoystick.js.map
  93363. var BABYLON;
  93364. (function (BABYLON) {
  93365. // We're mainly based on the logic defined into the FreeCamera code
  93366. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  93367. __extends(VirtualJoysticksCamera, _super);
  93368. function VirtualJoysticksCamera(name, position, scene) {
  93369. var _this = _super.call(this, name, position, scene) || this;
  93370. _this.inputs.addVirtualJoystick();
  93371. return _this;
  93372. }
  93373. VirtualJoysticksCamera.prototype.getClassName = function () {
  93374. return "VirtualJoysticksCamera";
  93375. };
  93376. return VirtualJoysticksCamera;
  93377. }(BABYLON.FreeCamera));
  93378. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  93379. })(BABYLON || (BABYLON = {}));
  93380. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  93381. var BABYLON;
  93382. (function (BABYLON) {
  93383. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  93384. function FreeCameraVirtualJoystickInput() {
  93385. }
  93386. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  93387. return this._leftjoystick;
  93388. };
  93389. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  93390. return this._rightjoystick;
  93391. };
  93392. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  93393. if (this._leftjoystick) {
  93394. var camera = this.camera;
  93395. var speed = camera._computeLocalCameraSpeed() * 50;
  93396. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  93397. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  93398. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  93399. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  93400. if (!this._leftjoystick.pressed) {
  93401. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  93402. }
  93403. if (!this._rightjoystick.pressed) {
  93404. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  93405. }
  93406. }
  93407. };
  93408. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  93409. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  93410. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  93411. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  93412. this._leftjoystick.setJoystickSensibility(0.15);
  93413. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  93414. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  93415. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  93416. this._rightjoystick.reverseUpDown = true;
  93417. this._rightjoystick.setJoystickSensibility(0.05);
  93418. this._rightjoystick.setJoystickColor("yellow");
  93419. };
  93420. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  93421. this._leftjoystick.releaseCanvas();
  93422. this._rightjoystick.releaseCanvas();
  93423. };
  93424. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  93425. return "FreeCameraVirtualJoystickInput";
  93426. };
  93427. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  93428. return "virtualJoystick";
  93429. };
  93430. return FreeCameraVirtualJoystickInput;
  93431. }());
  93432. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  93433. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  93434. })(BABYLON || (BABYLON = {}));
  93435. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  93436. var BABYLON;
  93437. (function (BABYLON) {
  93438. var SimplificationSettings = /** @class */ (function () {
  93439. function SimplificationSettings(quality, distance, optimizeMesh) {
  93440. this.quality = quality;
  93441. this.distance = distance;
  93442. this.optimizeMesh = optimizeMesh;
  93443. }
  93444. return SimplificationSettings;
  93445. }());
  93446. BABYLON.SimplificationSettings = SimplificationSettings;
  93447. var SimplificationQueue = /** @class */ (function () {
  93448. function SimplificationQueue() {
  93449. this.running = false;
  93450. this._simplificationArray = [];
  93451. }
  93452. SimplificationQueue.prototype.addTask = function (task) {
  93453. this._simplificationArray.push(task);
  93454. };
  93455. SimplificationQueue.prototype.executeNext = function () {
  93456. var task = this._simplificationArray.pop();
  93457. if (task) {
  93458. this.running = true;
  93459. this.runSimplification(task);
  93460. }
  93461. else {
  93462. this.running = false;
  93463. }
  93464. };
  93465. SimplificationQueue.prototype.runSimplification = function (task) {
  93466. var _this = this;
  93467. if (task.parallelProcessing) {
  93468. //parallel simplifier
  93469. task.settings.forEach(function (setting) {
  93470. var simplifier = _this.getSimplifier(task);
  93471. simplifier.simplify(setting, function (newMesh) {
  93472. task.mesh.addLODLevel(setting.distance, newMesh);
  93473. newMesh.isVisible = true;
  93474. //check if it is the last
  93475. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  93476. //all done, run the success callback.
  93477. task.successCallback();
  93478. }
  93479. _this.executeNext();
  93480. });
  93481. });
  93482. }
  93483. else {
  93484. //single simplifier.
  93485. var simplifier = this.getSimplifier(task);
  93486. var runDecimation = function (setting, callback) {
  93487. simplifier.simplify(setting, function (newMesh) {
  93488. task.mesh.addLODLevel(setting.distance, newMesh);
  93489. newMesh.isVisible = true;
  93490. //run the next quality level
  93491. callback();
  93492. });
  93493. };
  93494. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  93495. runDecimation(task.settings[loop.index], function () {
  93496. loop.executeNext();
  93497. });
  93498. }, function () {
  93499. //execution ended, run the success callback.
  93500. if (task.successCallback) {
  93501. task.successCallback();
  93502. }
  93503. _this.executeNext();
  93504. });
  93505. }
  93506. };
  93507. SimplificationQueue.prototype.getSimplifier = function (task) {
  93508. switch (task.simplificationType) {
  93509. case SimplificationType.QUADRATIC:
  93510. default:
  93511. return new QuadraticErrorSimplification(task.mesh);
  93512. }
  93513. };
  93514. return SimplificationQueue;
  93515. }());
  93516. BABYLON.SimplificationQueue = SimplificationQueue;
  93517. /**
  93518. * The implemented types of simplification
  93519. * At the moment only Quadratic Error Decimation is implemented
  93520. */
  93521. var SimplificationType;
  93522. (function (SimplificationType) {
  93523. /** Quadratic error decimation */
  93524. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  93525. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  93526. var DecimationTriangle = /** @class */ (function () {
  93527. function DecimationTriangle(vertices) {
  93528. this.vertices = vertices;
  93529. this.error = new Array(4);
  93530. this.deleted = false;
  93531. this.isDirty = false;
  93532. this.deletePending = false;
  93533. this.borderFactor = 0;
  93534. }
  93535. return DecimationTriangle;
  93536. }());
  93537. BABYLON.DecimationTriangle = DecimationTriangle;
  93538. var DecimationVertex = /** @class */ (function () {
  93539. function DecimationVertex(position, id) {
  93540. this.position = position;
  93541. this.id = id;
  93542. this.isBorder = true;
  93543. this.q = new QuadraticMatrix();
  93544. this.triangleCount = 0;
  93545. this.triangleStart = 0;
  93546. this.originalOffsets = [];
  93547. }
  93548. DecimationVertex.prototype.updatePosition = function (newPosition) {
  93549. this.position.copyFrom(newPosition);
  93550. };
  93551. return DecimationVertex;
  93552. }());
  93553. BABYLON.DecimationVertex = DecimationVertex;
  93554. var QuadraticMatrix = /** @class */ (function () {
  93555. function QuadraticMatrix(data) {
  93556. this.data = new Array(10);
  93557. for (var i = 0; i < 10; ++i) {
  93558. if (data && data[i]) {
  93559. this.data[i] = data[i];
  93560. }
  93561. else {
  93562. this.data[i] = 0;
  93563. }
  93564. }
  93565. }
  93566. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  93567. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  93568. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  93569. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  93570. return det;
  93571. };
  93572. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  93573. for (var i = 0; i < 10; ++i) {
  93574. this.data[i] += matrix.data[i];
  93575. }
  93576. };
  93577. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  93578. for (var i = 0; i < 10; ++i) {
  93579. this.data[i] += data[i];
  93580. }
  93581. };
  93582. QuadraticMatrix.prototype.add = function (matrix) {
  93583. var m = new QuadraticMatrix();
  93584. for (var i = 0; i < 10; ++i) {
  93585. m.data[i] = this.data[i] + matrix.data[i];
  93586. }
  93587. return m;
  93588. };
  93589. QuadraticMatrix.FromData = function (a, b, c, d) {
  93590. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  93591. };
  93592. //returning an array to avoid garbage collection
  93593. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  93594. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  93595. };
  93596. return QuadraticMatrix;
  93597. }());
  93598. BABYLON.QuadraticMatrix = QuadraticMatrix;
  93599. var Reference = /** @class */ (function () {
  93600. function Reference(vertexId, triangleId) {
  93601. this.vertexId = vertexId;
  93602. this.triangleId = triangleId;
  93603. }
  93604. return Reference;
  93605. }());
  93606. BABYLON.Reference = Reference;
  93607. /**
  93608. * An implementation of the Quadratic Error simplification algorithm.
  93609. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  93610. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  93611. * @author RaananW
  93612. */
  93613. var QuadraticErrorSimplification = /** @class */ (function () {
  93614. function QuadraticErrorSimplification(_mesh) {
  93615. this._mesh = _mesh;
  93616. this.syncIterations = 5000;
  93617. this.aggressiveness = 7;
  93618. this.decimationIterations = 100;
  93619. this.boundingBoxEpsilon = BABYLON.Epsilon;
  93620. }
  93621. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  93622. var _this = this;
  93623. this.initDecimatedMesh();
  93624. //iterating through the submeshes array, one after the other.
  93625. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  93626. _this.initWithMesh(loop.index, function () {
  93627. _this.runDecimation(settings, loop.index, function () {
  93628. loop.executeNext();
  93629. });
  93630. }, settings.optimizeMesh);
  93631. }, function () {
  93632. setTimeout(function () {
  93633. successCallback(_this._reconstructedMesh);
  93634. }, 0);
  93635. });
  93636. };
  93637. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  93638. var _this = this;
  93639. var targetCount = ~~(this.triangles.length * settings.quality);
  93640. var deletedTriangles = 0;
  93641. var triangleCount = this.triangles.length;
  93642. var iterationFunction = function (iteration, callback) {
  93643. setTimeout(function () {
  93644. if (iteration % 5 === 0) {
  93645. _this.updateMesh(iteration === 0);
  93646. }
  93647. for (var i = 0; i < _this.triangles.length; ++i) {
  93648. _this.triangles[i].isDirty = false;
  93649. }
  93650. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  93651. var trianglesIterator = function (i) {
  93652. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  93653. var t = _this.triangles[tIdx];
  93654. if (!t)
  93655. return;
  93656. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  93657. return;
  93658. }
  93659. for (var j = 0; j < 3; ++j) {
  93660. if (t.error[j] < threshold) {
  93661. var deleted0 = [];
  93662. var deleted1 = [];
  93663. var v0 = t.vertices[j];
  93664. var v1 = t.vertices[(j + 1) % 3];
  93665. if (v0.isBorder || v1.isBorder)
  93666. continue;
  93667. var p = BABYLON.Vector3.Zero();
  93668. var n = BABYLON.Vector3.Zero();
  93669. var uv = BABYLON.Vector2.Zero();
  93670. var color = new BABYLON.Color4(0, 0, 0, 1);
  93671. _this.calculateError(v0, v1, p, n, uv, color);
  93672. var delTr = new Array();
  93673. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  93674. continue;
  93675. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  93676. continue;
  93677. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  93678. continue;
  93679. var uniqueArray = new Array();
  93680. delTr.forEach(function (deletedT) {
  93681. if (uniqueArray.indexOf(deletedT) === -1) {
  93682. deletedT.deletePending = true;
  93683. uniqueArray.push(deletedT);
  93684. }
  93685. });
  93686. if (uniqueArray.length % 2 !== 0) {
  93687. continue;
  93688. }
  93689. v0.q = v1.q.add(v0.q);
  93690. v0.updatePosition(p);
  93691. var tStart = _this.references.length;
  93692. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  93693. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  93694. var tCount = _this.references.length - tStart;
  93695. if (tCount <= v0.triangleCount) {
  93696. if (tCount) {
  93697. for (var c = 0; c < tCount; c++) {
  93698. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  93699. }
  93700. }
  93701. }
  93702. else {
  93703. v0.triangleStart = tStart;
  93704. }
  93705. v0.triangleCount = tCount;
  93706. break;
  93707. }
  93708. }
  93709. };
  93710. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  93711. }, 0);
  93712. };
  93713. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  93714. if (triangleCount - deletedTriangles <= targetCount)
  93715. loop.breakLoop();
  93716. else {
  93717. iterationFunction(loop.index, function () {
  93718. loop.executeNext();
  93719. });
  93720. }
  93721. }, function () {
  93722. setTimeout(function () {
  93723. //reconstruct this part of the mesh
  93724. _this.reconstructMesh(submeshIndex);
  93725. successCallback();
  93726. }, 0);
  93727. });
  93728. };
  93729. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  93730. var _this = this;
  93731. this.vertices = [];
  93732. this.triangles = [];
  93733. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93734. var indices = this._mesh.getIndices();
  93735. var submesh = this._mesh.subMeshes[submeshIndex];
  93736. var findInVertices = function (positionToSearch) {
  93737. if (optimizeMesh) {
  93738. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  93739. if (_this.vertices[ii].position.equals(positionToSearch)) {
  93740. return _this.vertices[ii];
  93741. }
  93742. }
  93743. }
  93744. return null;
  93745. };
  93746. var vertexReferences = [];
  93747. var vertexInit = function (i) {
  93748. if (!positionData) {
  93749. return;
  93750. }
  93751. var offset = i + submesh.verticesStart;
  93752. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  93753. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  93754. vertex.originalOffsets.push(offset);
  93755. if (vertex.id === _this.vertices.length) {
  93756. _this.vertices.push(vertex);
  93757. }
  93758. vertexReferences.push(vertex.id);
  93759. };
  93760. //var totalVertices = mesh.getTotalVertices();
  93761. var totalVertices = submesh.verticesCount;
  93762. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  93763. var indicesInit = function (i) {
  93764. if (!indices) {
  93765. return;
  93766. }
  93767. var offset = (submesh.indexStart / 3) + i;
  93768. var pos = (offset * 3);
  93769. var i0 = indices[pos + 0];
  93770. var i1 = indices[pos + 1];
  93771. var i2 = indices[pos + 2];
  93772. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  93773. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  93774. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  93775. var triangle = new DecimationTriangle([v0, v1, v2]);
  93776. triangle.originalOffset = pos;
  93777. _this.triangles.push(triangle);
  93778. };
  93779. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  93780. _this.init(callback);
  93781. });
  93782. });
  93783. };
  93784. QuadraticErrorSimplification.prototype.init = function (callback) {
  93785. var _this = this;
  93786. var triangleInit1 = function (i) {
  93787. var t = _this.triangles[i];
  93788. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  93789. for (var j = 0; j < 3; j++) {
  93790. 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))));
  93791. }
  93792. };
  93793. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  93794. var triangleInit2 = function (i) {
  93795. var t = _this.triangles[i];
  93796. for (var j = 0; j < 3; ++j) {
  93797. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  93798. }
  93799. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93800. };
  93801. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  93802. callback();
  93803. });
  93804. });
  93805. };
  93806. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  93807. var newTriangles = [];
  93808. var i;
  93809. for (i = 0; i < this.vertices.length; ++i) {
  93810. this.vertices[i].triangleCount = 0;
  93811. }
  93812. var t;
  93813. var j;
  93814. for (i = 0; i < this.triangles.length; ++i) {
  93815. if (!this.triangles[i].deleted) {
  93816. t = this.triangles[i];
  93817. for (j = 0; j < 3; ++j) {
  93818. t.vertices[j].triangleCount = 1;
  93819. }
  93820. newTriangles.push(t);
  93821. }
  93822. }
  93823. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  93824. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  93825. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  93826. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  93827. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  93828. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93829. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  93830. var vertexCount = 0;
  93831. for (i = 0; i < this.vertices.length; ++i) {
  93832. var vertex = this.vertices[i];
  93833. vertex.id = vertexCount;
  93834. if (vertex.triangleCount) {
  93835. vertex.originalOffsets.forEach(function (originalOffset) {
  93836. if (!normalData) {
  93837. return;
  93838. }
  93839. newPositionData.push(vertex.position.x);
  93840. newPositionData.push(vertex.position.y);
  93841. newPositionData.push(vertex.position.z);
  93842. newNormalData.push(normalData[originalOffset * 3]);
  93843. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  93844. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  93845. if (uvs && uvs.length) {
  93846. newUVsData.push(uvs[(originalOffset * 2)]);
  93847. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  93848. }
  93849. else if (colorsData && colorsData.length) {
  93850. newColorsData.push(colorsData[(originalOffset * 4)]);
  93851. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  93852. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  93853. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  93854. }
  93855. ++vertexCount;
  93856. });
  93857. }
  93858. }
  93859. var startingIndex = this._reconstructedMesh.getTotalIndices();
  93860. var startingVertex = this._reconstructedMesh.getTotalVertices();
  93861. var submeshesArray = this._reconstructedMesh.subMeshes;
  93862. this._reconstructedMesh.subMeshes = [];
  93863. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  93864. var originalIndices = this._mesh.getIndices();
  93865. for (i = 0; i < newTriangles.length; ++i) {
  93866. t = newTriangles[i]; //now get the new referencing point for each vertex
  93867. [0, 1, 2].forEach(function (idx) {
  93868. var id = originalIndices[t.originalOffset + idx];
  93869. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  93870. if (offset < 0)
  93871. offset = 0;
  93872. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  93873. });
  93874. }
  93875. //overwriting the old vertex buffers and indices.
  93876. this._reconstructedMesh.setIndices(newIndicesArray);
  93877. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  93878. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  93879. if (newUVsData.length > 0)
  93880. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  93881. if (newColorsData.length > 0)
  93882. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  93883. //create submesh
  93884. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  93885. if (submeshIndex > 0) {
  93886. this._reconstructedMesh.subMeshes = [];
  93887. submeshesArray.forEach(function (submesh) {
  93888. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  93889. });
  93890. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  93891. }
  93892. };
  93893. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  93894. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  93895. this._reconstructedMesh.material = this._mesh.material;
  93896. this._reconstructedMesh.parent = this._mesh.parent;
  93897. this._reconstructedMesh.isVisible = false;
  93898. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  93899. };
  93900. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  93901. for (var i = 0; i < vertex1.triangleCount; ++i) {
  93902. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  93903. if (t.deleted)
  93904. continue;
  93905. var s = this.references[vertex1.triangleStart + i].vertexId;
  93906. var v1 = t.vertices[(s + 1) % 3];
  93907. var v2 = t.vertices[(s + 2) % 3];
  93908. if ((v1 === vertex2 || v2 === vertex2)) {
  93909. deletedArray[i] = true;
  93910. delTr.push(t);
  93911. continue;
  93912. }
  93913. var d1 = v1.position.subtract(point);
  93914. d1 = d1.normalize();
  93915. var d2 = v2.position.subtract(point);
  93916. d2 = d2.normalize();
  93917. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  93918. return true;
  93919. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  93920. deletedArray[i] = false;
  93921. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  93922. return true;
  93923. }
  93924. return false;
  93925. };
  93926. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  93927. var newDeleted = deletedTriangles;
  93928. for (var i = 0; i < vertex.triangleCount; ++i) {
  93929. var ref = this.references[vertex.triangleStart + i];
  93930. var t = this.triangles[ref.triangleId];
  93931. if (t.deleted)
  93932. continue;
  93933. if (deletedArray[i] && t.deletePending) {
  93934. t.deleted = true;
  93935. newDeleted++;
  93936. continue;
  93937. }
  93938. t.vertices[ref.vertexId] = origVertex;
  93939. t.isDirty = true;
  93940. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  93941. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  93942. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  93943. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93944. this.references.push(ref);
  93945. }
  93946. return newDeleted;
  93947. };
  93948. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  93949. for (var i = 0; i < this.vertices.length; ++i) {
  93950. var vCount = [];
  93951. var vId = [];
  93952. var v = this.vertices[i];
  93953. var j;
  93954. for (j = 0; j < v.triangleCount; ++j) {
  93955. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  93956. for (var ii = 0; ii < 3; ii++) {
  93957. var ofs = 0;
  93958. var vv = triangle.vertices[ii];
  93959. while (ofs < vCount.length) {
  93960. if (vId[ofs] === vv.id)
  93961. break;
  93962. ++ofs;
  93963. }
  93964. if (ofs === vCount.length) {
  93965. vCount.push(1);
  93966. vId.push(vv.id);
  93967. }
  93968. else {
  93969. vCount[ofs]++;
  93970. }
  93971. }
  93972. }
  93973. for (j = 0; j < vCount.length; ++j) {
  93974. if (vCount[j] === 1) {
  93975. this.vertices[vId[j]].isBorder = true;
  93976. }
  93977. else {
  93978. this.vertices[vId[j]].isBorder = false;
  93979. }
  93980. }
  93981. }
  93982. };
  93983. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  93984. if (identifyBorders === void 0) { identifyBorders = false; }
  93985. var i;
  93986. if (!identifyBorders) {
  93987. var newTrianglesVector = [];
  93988. for (i = 0; i < this.triangles.length; ++i) {
  93989. if (!this.triangles[i].deleted) {
  93990. newTrianglesVector.push(this.triangles[i]);
  93991. }
  93992. }
  93993. this.triangles = newTrianglesVector;
  93994. }
  93995. for (i = 0; i < this.vertices.length; ++i) {
  93996. this.vertices[i].triangleCount = 0;
  93997. this.vertices[i].triangleStart = 0;
  93998. }
  93999. var t;
  94000. var j;
  94001. var v;
  94002. for (i = 0; i < this.triangles.length; ++i) {
  94003. t = this.triangles[i];
  94004. for (j = 0; j < 3; ++j) {
  94005. v = t.vertices[j];
  94006. v.triangleCount++;
  94007. }
  94008. }
  94009. var tStart = 0;
  94010. for (i = 0; i < this.vertices.length; ++i) {
  94011. this.vertices[i].triangleStart = tStart;
  94012. tStart += this.vertices[i].triangleCount;
  94013. this.vertices[i].triangleCount = 0;
  94014. }
  94015. var newReferences = new Array(this.triangles.length * 3);
  94016. for (i = 0; i < this.triangles.length; ++i) {
  94017. t = this.triangles[i];
  94018. for (j = 0; j < 3; ++j) {
  94019. v = t.vertices[j];
  94020. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94021. v.triangleCount++;
  94022. }
  94023. }
  94024. this.references = newReferences;
  94025. if (identifyBorders) {
  94026. this.identifyBorder();
  94027. }
  94028. };
  94029. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94030. var x = point.x;
  94031. var y = point.y;
  94032. var z = point.z;
  94033. 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
  94034. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94035. };
  94036. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94037. var q = vertex1.q.add(vertex2.q);
  94038. var border = vertex1.isBorder && vertex2.isBorder;
  94039. var error = 0;
  94040. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94041. if (qDet !== 0 && !border) {
  94042. if (!pointResult) {
  94043. pointResult = BABYLON.Vector3.Zero();
  94044. }
  94045. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94046. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94047. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94048. error = this.vertexError(q, pointResult);
  94049. }
  94050. else {
  94051. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94052. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94053. var error1 = this.vertexError(q, vertex1.position);
  94054. var error2 = this.vertexError(q, vertex2.position);
  94055. var error3 = this.vertexError(q, p3);
  94056. error = Math.min(error1, error2, error3);
  94057. if (error === error1) {
  94058. if (pointResult) {
  94059. pointResult.copyFrom(vertex1.position);
  94060. }
  94061. }
  94062. else if (error === error2) {
  94063. if (pointResult) {
  94064. pointResult.copyFrom(vertex2.position);
  94065. }
  94066. }
  94067. else {
  94068. if (pointResult) {
  94069. pointResult.copyFrom(p3);
  94070. }
  94071. }
  94072. }
  94073. return error;
  94074. };
  94075. return QuadraticErrorSimplification;
  94076. }());
  94077. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94078. })(BABYLON || (BABYLON = {}));
  94079. //# sourceMappingURL=babylon.meshSimplification.js.map
  94080. var BABYLON;
  94081. (function (BABYLON) {
  94082. var MeshLODLevel = /** @class */ (function () {
  94083. function MeshLODLevel(distance, mesh) {
  94084. this.distance = distance;
  94085. this.mesh = mesh;
  94086. }
  94087. return MeshLODLevel;
  94088. }());
  94089. BABYLON.MeshLODLevel = MeshLODLevel;
  94090. })(BABYLON || (BABYLON = {}));
  94091. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94092. var BABYLON;
  94093. (function (BABYLON) {
  94094. /**
  94095. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94096. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94097. */
  94098. var SceneOptimization = /** @class */ (function () {
  94099. /**
  94100. * Creates the SceneOptimization object
  94101. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94102. * @param desc defines the description associated with the optimization
  94103. */
  94104. function SceneOptimization(
  94105. /**
  94106. * Defines the priority of this optimization (0 by default which means first in the list)
  94107. */
  94108. priority) {
  94109. if (priority === void 0) { priority = 0; }
  94110. this.priority = priority;
  94111. }
  94112. /**
  94113. * Gets a string describing the action executed by the current optimization
  94114. * @returns description string
  94115. */
  94116. SceneOptimization.prototype.getDescription = function () {
  94117. return "";
  94118. };
  94119. /**
  94120. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94121. * @param scene defines the current scene where to apply this optimization
  94122. * @param optimizer defines the current optimizer
  94123. * @returns true if everything that can be done was applied
  94124. */
  94125. SceneOptimization.prototype.apply = function (scene, optimizer) {
  94126. return true;
  94127. };
  94128. ;
  94129. return SceneOptimization;
  94130. }());
  94131. BABYLON.SceneOptimization = SceneOptimization;
  94132. /**
  94133. * Defines an optimization used to reduce the size of render target textures
  94134. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94135. */
  94136. var TextureOptimization = /** @class */ (function (_super) {
  94137. __extends(TextureOptimization, _super);
  94138. /**
  94139. * Creates the TextureOptimization object
  94140. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94141. * @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
  94142. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94143. */
  94144. function TextureOptimization(
  94145. /**
  94146. * Defines the priority of this optimization (0 by default which means first in the list)
  94147. */
  94148. priority,
  94149. /**
  94150. * 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
  94151. */
  94152. maximumSize,
  94153. /**
  94154. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94155. */
  94156. step) {
  94157. if (priority === void 0) { priority = 0; }
  94158. if (maximumSize === void 0) { maximumSize = 1024; }
  94159. if (step === void 0) { step = 0.5; }
  94160. var _this = _super.call(this, priority) || this;
  94161. _this.priority = priority;
  94162. _this.maximumSize = maximumSize;
  94163. _this.step = step;
  94164. return _this;
  94165. }
  94166. /**
  94167. * Gets a string describing the action executed by the current optimization
  94168. * @returns description string
  94169. */
  94170. TextureOptimization.prototype.getDescription = function () {
  94171. return "Reducing render target texture size to " + this.maximumSize;
  94172. };
  94173. /**
  94174. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94175. * @param scene defines the current scene where to apply this optimization
  94176. * @param optimizer defines the current optimizer
  94177. * @returns true if everything that can be done was applied
  94178. */
  94179. TextureOptimization.prototype.apply = function (scene, optimizer) {
  94180. var allDone = true;
  94181. for (var index = 0; index < scene.textures.length; index++) {
  94182. var texture = scene.textures[index];
  94183. if (!texture.canRescale || texture.getContext) {
  94184. continue;
  94185. }
  94186. var currentSize = texture.getSize();
  94187. var maxDimension = Math.max(currentSize.width, currentSize.height);
  94188. if (maxDimension > this.maximumSize) {
  94189. texture.scale(this.step);
  94190. allDone = false;
  94191. }
  94192. }
  94193. return allDone;
  94194. };
  94195. return TextureOptimization;
  94196. }(SceneOptimization));
  94197. BABYLON.TextureOptimization = TextureOptimization;
  94198. /**
  94199. * Defines an optimization used to increase or decrease the rendering resolution
  94200. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94201. */
  94202. var HardwareScalingOptimization = /** @class */ (function (_super) {
  94203. __extends(HardwareScalingOptimization, _super);
  94204. /**
  94205. * Creates the HardwareScalingOptimization object
  94206. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94207. * @param maximumScale defines the maximum scale to use (2 by default)
  94208. * @param step defines the step to use between two passes (0.5 by default)
  94209. */
  94210. function HardwareScalingOptimization(
  94211. /**
  94212. * Defines the priority of this optimization (0 by default which means first in the list)
  94213. */
  94214. priority,
  94215. /**
  94216. * Defines the maximum scale to use (2 by default)
  94217. */
  94218. maximumScale,
  94219. /**
  94220. * Defines the step to use between two passes (0.5 by default)
  94221. */
  94222. step) {
  94223. if (priority === void 0) { priority = 0; }
  94224. if (maximumScale === void 0) { maximumScale = 2; }
  94225. if (step === void 0) { step = 0.25; }
  94226. var _this = _super.call(this, priority) || this;
  94227. _this.priority = priority;
  94228. _this.maximumScale = maximumScale;
  94229. _this.step = step;
  94230. _this._currentScale = -1;
  94231. _this._directionOffset = 1;
  94232. return _this;
  94233. }
  94234. /**
  94235. * Gets a string describing the action executed by the current optimization
  94236. * @return description string
  94237. */
  94238. HardwareScalingOptimization.prototype.getDescription = function () {
  94239. return "Setting hardware scaling level to " + this._currentScale;
  94240. };
  94241. /**
  94242. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94243. * @param scene defines the current scene where to apply this optimization
  94244. * @param optimizer defines the current optimizer
  94245. * @returns true if everything that can be done was applied
  94246. */
  94247. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  94248. if (this._currentScale === -1) {
  94249. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  94250. if (this._currentScale > this.maximumScale) {
  94251. this._directionOffset = -1;
  94252. }
  94253. }
  94254. this._currentScale += this._directionOffset * this.step;
  94255. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  94256. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  94257. };
  94258. ;
  94259. return HardwareScalingOptimization;
  94260. }(SceneOptimization));
  94261. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  94262. /**
  94263. * Defines an optimization used to remove shadows
  94264. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94265. */
  94266. var ShadowsOptimization = /** @class */ (function (_super) {
  94267. __extends(ShadowsOptimization, _super);
  94268. function ShadowsOptimization() {
  94269. return _super !== null && _super.apply(this, arguments) || this;
  94270. }
  94271. /**
  94272. * Gets a string describing the action executed by the current optimization
  94273. * @return description string
  94274. */
  94275. ShadowsOptimization.prototype.getDescription = function () {
  94276. return "Turning shadows on/off";
  94277. };
  94278. /**
  94279. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94280. * @param scene defines the current scene where to apply this optimization
  94281. * @param optimizer defines the current optimizer
  94282. * @returns true if everything that can be done was applied
  94283. */
  94284. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  94285. scene.shadowsEnabled = optimizer.isInImprovementMode;
  94286. return true;
  94287. };
  94288. ;
  94289. return ShadowsOptimization;
  94290. }(SceneOptimization));
  94291. BABYLON.ShadowsOptimization = ShadowsOptimization;
  94292. /**
  94293. * Defines an optimization used to turn post-processes off
  94294. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94295. */
  94296. var PostProcessesOptimization = /** @class */ (function (_super) {
  94297. __extends(PostProcessesOptimization, _super);
  94298. function PostProcessesOptimization() {
  94299. return _super !== null && _super.apply(this, arguments) || this;
  94300. }
  94301. /**
  94302. * Gets a string describing the action executed by the current optimization
  94303. * @return description string
  94304. */
  94305. PostProcessesOptimization.prototype.getDescription = function () {
  94306. return "Turning post-processes on/off";
  94307. };
  94308. /**
  94309. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94310. * @param scene defines the current scene where to apply this optimization
  94311. * @param optimizer defines the current optimizer
  94312. * @returns true if everything that can be done was applied
  94313. */
  94314. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  94315. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  94316. return true;
  94317. };
  94318. ;
  94319. return PostProcessesOptimization;
  94320. }(SceneOptimization));
  94321. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  94322. /**
  94323. * Defines an optimization used to turn lens flares off
  94324. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94325. */
  94326. var LensFlaresOptimization = /** @class */ (function (_super) {
  94327. __extends(LensFlaresOptimization, _super);
  94328. function LensFlaresOptimization() {
  94329. return _super !== null && _super.apply(this, arguments) || this;
  94330. }
  94331. /**
  94332. * Gets a string describing the action executed by the current optimization
  94333. * @return description string
  94334. */
  94335. LensFlaresOptimization.prototype.getDescription = function () {
  94336. return "Turning lens flares on/off";
  94337. };
  94338. /**
  94339. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94340. * @param scene defines the current scene where to apply this optimization
  94341. * @param optimizer defines the current optimizer
  94342. * @returns true if everything that can be done was applied
  94343. */
  94344. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  94345. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  94346. return true;
  94347. };
  94348. ;
  94349. return LensFlaresOptimization;
  94350. }(SceneOptimization));
  94351. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  94352. /**
  94353. * Defines an optimization based on user defined callback.
  94354. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94355. */
  94356. var CustomOptimization = /** @class */ (function (_super) {
  94357. __extends(CustomOptimization, _super);
  94358. function CustomOptimization() {
  94359. return _super !== null && _super.apply(this, arguments) || this;
  94360. }
  94361. /**
  94362. * Gets a string describing the action executed by the current optimization
  94363. * @returns description string
  94364. */
  94365. CustomOptimization.prototype.getDescription = function () {
  94366. if (this.onGetDescription) {
  94367. return this.onGetDescription();
  94368. }
  94369. return "Running user defined callback";
  94370. };
  94371. /**
  94372. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94373. * @param scene defines the current scene where to apply this optimization
  94374. * @param optimizer defines the current optimizer
  94375. * @returns true if everything that can be done was applied
  94376. */
  94377. CustomOptimization.prototype.apply = function (scene, optimizer) {
  94378. if (this.onApply) {
  94379. return this.onApply(scene, optimizer);
  94380. }
  94381. return true;
  94382. };
  94383. ;
  94384. return CustomOptimization;
  94385. }(SceneOptimization));
  94386. BABYLON.CustomOptimization = CustomOptimization;
  94387. /**
  94388. * Defines an optimization used to turn particles off
  94389. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94390. */
  94391. var ParticlesOptimization = /** @class */ (function (_super) {
  94392. __extends(ParticlesOptimization, _super);
  94393. function ParticlesOptimization() {
  94394. return _super !== null && _super.apply(this, arguments) || this;
  94395. }
  94396. /**
  94397. * Gets a string describing the action executed by the current optimization
  94398. * @return description string
  94399. */
  94400. ParticlesOptimization.prototype.getDescription = function () {
  94401. return "Turning particles on/off";
  94402. };
  94403. /**
  94404. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94405. * @param scene defines the current scene where to apply this optimization
  94406. * @param optimizer defines the current optimizer
  94407. * @returns true if everything that can be done was applied
  94408. */
  94409. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  94410. scene.particlesEnabled = optimizer.isInImprovementMode;
  94411. return true;
  94412. };
  94413. ;
  94414. return ParticlesOptimization;
  94415. }(SceneOptimization));
  94416. BABYLON.ParticlesOptimization = ParticlesOptimization;
  94417. /**
  94418. * Defines an optimization used to turn render targets off
  94419. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94420. */
  94421. var RenderTargetsOptimization = /** @class */ (function (_super) {
  94422. __extends(RenderTargetsOptimization, _super);
  94423. function RenderTargetsOptimization() {
  94424. return _super !== null && _super.apply(this, arguments) || this;
  94425. }
  94426. /**
  94427. * Gets a string describing the action executed by the current optimization
  94428. * @return description string
  94429. */
  94430. RenderTargetsOptimization.prototype.getDescription = function () {
  94431. return "Turning render targets off";
  94432. };
  94433. /**
  94434. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94435. * @param scene defines the current scene where to apply this optimization
  94436. * @param optimizer defines the current optimizer
  94437. * @returns true if everything that can be done was applied
  94438. */
  94439. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  94440. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  94441. return true;
  94442. };
  94443. ;
  94444. return RenderTargetsOptimization;
  94445. }(SceneOptimization));
  94446. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  94447. /**
  94448. * Defines an optimization used to merge meshes with compatible materials
  94449. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94450. */
  94451. var MergeMeshesOptimization = /** @class */ (function (_super) {
  94452. __extends(MergeMeshesOptimization, _super);
  94453. function MergeMeshesOptimization() {
  94454. var _this = _super !== null && _super.apply(this, arguments) || this;
  94455. _this._canBeMerged = function (abstractMesh) {
  94456. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  94457. return false;
  94458. }
  94459. var mesh = abstractMesh;
  94460. if (!mesh.isVisible || !mesh.isEnabled()) {
  94461. return false;
  94462. }
  94463. if (mesh.instances.length > 0) {
  94464. return false;
  94465. }
  94466. if (mesh.skeleton || mesh.hasLODLevels) {
  94467. return false;
  94468. }
  94469. if (mesh.parent) {
  94470. return false;
  94471. }
  94472. return true;
  94473. };
  94474. return _this;
  94475. }
  94476. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  94477. /**
  94478. * Gets or sets a boolean which defines if optimization octree has to be updated
  94479. */
  94480. get: function () {
  94481. return MergeMeshesOptimization._UpdateSelectionTree;
  94482. },
  94483. /**
  94484. * Gets or sets a boolean which defines if optimization octree has to be updated
  94485. */
  94486. set: function (value) {
  94487. MergeMeshesOptimization._UpdateSelectionTree = value;
  94488. },
  94489. enumerable: true,
  94490. configurable: true
  94491. });
  94492. /**
  94493. * Gets a string describing the action executed by the current optimization
  94494. * @return description string
  94495. */
  94496. MergeMeshesOptimization.prototype.getDescription = function () {
  94497. return "Merging similar meshes together";
  94498. };
  94499. /**
  94500. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94501. * @param scene defines the current scene where to apply this optimization
  94502. * @param optimizer defines the current optimizer
  94503. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  94504. * @returns true if everything that can be done was applied
  94505. */
  94506. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  94507. var globalPool = scene.meshes.slice(0);
  94508. var globalLength = globalPool.length;
  94509. for (var index = 0; index < globalLength; index++) {
  94510. var currentPool = new Array();
  94511. var current = globalPool[index];
  94512. // Checks
  94513. if (!this._canBeMerged(current)) {
  94514. continue;
  94515. }
  94516. currentPool.push(current);
  94517. // Find compatible meshes
  94518. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  94519. var otherMesh = globalPool[subIndex];
  94520. if (!this._canBeMerged(otherMesh)) {
  94521. continue;
  94522. }
  94523. if (otherMesh.material !== current.material) {
  94524. continue;
  94525. }
  94526. if (otherMesh.checkCollisions !== current.checkCollisions) {
  94527. continue;
  94528. }
  94529. currentPool.push(otherMesh);
  94530. globalLength--;
  94531. globalPool.splice(subIndex, 1);
  94532. subIndex--;
  94533. }
  94534. if (currentPool.length < 2) {
  94535. continue;
  94536. }
  94537. // Merge meshes
  94538. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  94539. }
  94540. if (updateSelectionTree != undefined) {
  94541. if (updateSelectionTree) {
  94542. scene.createOrUpdateSelectionOctree();
  94543. }
  94544. }
  94545. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  94546. scene.createOrUpdateSelectionOctree();
  94547. }
  94548. return true;
  94549. };
  94550. ;
  94551. MergeMeshesOptimization._UpdateSelectionTree = false;
  94552. return MergeMeshesOptimization;
  94553. }(SceneOptimization));
  94554. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  94555. /**
  94556. * Defines a list of options used by SceneOptimizer
  94557. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94558. */
  94559. var SceneOptimizerOptions = /** @class */ (function () {
  94560. /**
  94561. * Creates a new list of options used by SceneOptimizer
  94562. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  94563. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  94564. */
  94565. function SceneOptimizerOptions(
  94566. /**
  94567. * Defines the target frame rate to reach (60 by default)
  94568. */
  94569. targetFrameRate,
  94570. /**
  94571. * Defines the interval between two checkes (2000ms by default)
  94572. */
  94573. trackerDuration) {
  94574. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  94575. if (trackerDuration === void 0) { trackerDuration = 2000; }
  94576. this.targetFrameRate = targetFrameRate;
  94577. this.trackerDuration = trackerDuration;
  94578. /**
  94579. * Gets the list of optimizations to apply
  94580. */
  94581. this.optimizations = new Array();
  94582. }
  94583. /**
  94584. * Add a new optimization
  94585. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  94586. * @returns the current SceneOptimizerOptions
  94587. */
  94588. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  94589. this.optimizations.push(optimization);
  94590. return this;
  94591. };
  94592. /**
  94593. * Add a new custom optimization
  94594. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  94595. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  94596. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94597. * @returns the current SceneOptimizerOptions
  94598. */
  94599. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  94600. if (priority === void 0) { priority = 0; }
  94601. var optimization = new CustomOptimization(priority);
  94602. optimization.onApply = onApply;
  94603. optimization.onGetDescription = onGetDescription;
  94604. this.optimizations.push(optimization);
  94605. return this;
  94606. };
  94607. /**
  94608. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  94609. * @param targetFrameRate defines the target frame rate (60 by default)
  94610. * @returns a SceneOptimizerOptions object
  94611. */
  94612. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  94613. var result = new SceneOptimizerOptions(targetFrameRate);
  94614. var priority = 0;
  94615. result.addOptimization(new MergeMeshesOptimization(priority));
  94616. result.addOptimization(new ShadowsOptimization(priority));
  94617. result.addOptimization(new LensFlaresOptimization(priority));
  94618. // Next priority
  94619. priority++;
  94620. result.addOptimization(new PostProcessesOptimization(priority));
  94621. result.addOptimization(new ParticlesOptimization(priority));
  94622. // Next priority
  94623. priority++;
  94624. result.addOptimization(new TextureOptimization(priority, 1024));
  94625. return result;
  94626. };
  94627. /**
  94628. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  94629. * @param targetFrameRate defines the target frame rate (60 by default)
  94630. * @returns a SceneOptimizerOptions object
  94631. */
  94632. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  94633. var result = new SceneOptimizerOptions(targetFrameRate);
  94634. var priority = 0;
  94635. result.addOptimization(new MergeMeshesOptimization(priority));
  94636. result.addOptimization(new ShadowsOptimization(priority));
  94637. result.addOptimization(new LensFlaresOptimization(priority));
  94638. // Next priority
  94639. priority++;
  94640. result.addOptimization(new PostProcessesOptimization(priority));
  94641. result.addOptimization(new ParticlesOptimization(priority));
  94642. // Next priority
  94643. priority++;
  94644. result.addOptimization(new TextureOptimization(priority, 512));
  94645. // Next priority
  94646. priority++;
  94647. result.addOptimization(new RenderTargetsOptimization(priority));
  94648. // Next priority
  94649. priority++;
  94650. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  94651. return result;
  94652. };
  94653. /**
  94654. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  94655. * @param targetFrameRate defines the target frame rate (60 by default)
  94656. * @returns a SceneOptimizerOptions object
  94657. */
  94658. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  94659. var result = new SceneOptimizerOptions(targetFrameRate);
  94660. var priority = 0;
  94661. result.addOptimization(new MergeMeshesOptimization(priority));
  94662. result.addOptimization(new ShadowsOptimization(priority));
  94663. result.addOptimization(new LensFlaresOptimization(priority));
  94664. // Next priority
  94665. priority++;
  94666. result.addOptimization(new PostProcessesOptimization(priority));
  94667. result.addOptimization(new ParticlesOptimization(priority));
  94668. // Next priority
  94669. priority++;
  94670. result.addOptimization(new TextureOptimization(priority, 256));
  94671. // Next priority
  94672. priority++;
  94673. result.addOptimization(new RenderTargetsOptimization(priority));
  94674. // Next priority
  94675. priority++;
  94676. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  94677. return result;
  94678. };
  94679. return SceneOptimizerOptions;
  94680. }());
  94681. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  94682. /**
  94683. * Class used to run optimizations in order to reach a target frame rate
  94684. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94685. */
  94686. var SceneOptimizer = /** @class */ (function () {
  94687. /**
  94688. * Creates a new SceneOptimizer
  94689. * @param scene defines the scene to work on
  94690. * @param options defines the options to use with the SceneOptimizer
  94691. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  94692. * @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)
  94693. */
  94694. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  94695. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  94696. if (improvementMode === void 0) { improvementMode = false; }
  94697. var _this = this;
  94698. this._isRunning = false;
  94699. this._currentPriorityLevel = 0;
  94700. this._targetFrameRate = 60;
  94701. this._trackerDuration = 2000;
  94702. this._currentFrameRate = 0;
  94703. this._improvementMode = false;
  94704. /**
  94705. * Defines an observable called when the optimizer reaches the target frame rate
  94706. */
  94707. this.onSuccessObservable = new BABYLON.Observable();
  94708. /**
  94709. * Defines an observable called when the optimizer enables an optimization
  94710. */
  94711. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  94712. /**
  94713. * Defines an observable called when the optimizer is not able to reach the target frame rate
  94714. */
  94715. this.onFailureObservable = new BABYLON.Observable();
  94716. if (!options) {
  94717. this._options = new SceneOptimizerOptions();
  94718. }
  94719. else {
  94720. this._options = options;
  94721. }
  94722. if (this._options.targetFrameRate) {
  94723. this._targetFrameRate = this._options.targetFrameRate;
  94724. }
  94725. if (this._options.trackerDuration) {
  94726. this._trackerDuration = this._options.trackerDuration;
  94727. }
  94728. if (autoGeneratePriorities) {
  94729. var priority = 0;
  94730. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  94731. var optim = _a[_i];
  94732. optim.priority = priority++;
  94733. }
  94734. }
  94735. this._improvementMode = improvementMode;
  94736. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94737. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  94738. _this._sceneDisposeObserver = null;
  94739. _this.dispose();
  94740. });
  94741. }
  94742. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  94743. /**
  94744. * Gets a boolean indicating if the optimizer is in improvement mode
  94745. */
  94746. get: function () {
  94747. return this._improvementMode;
  94748. },
  94749. enumerable: true,
  94750. configurable: true
  94751. });
  94752. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  94753. /**
  94754. * Gets the current priority level (0 at start)
  94755. */
  94756. get: function () {
  94757. return this._currentPriorityLevel;
  94758. },
  94759. enumerable: true,
  94760. configurable: true
  94761. });
  94762. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  94763. /**
  94764. * Gets the current frame rate checked by the SceneOptimizer
  94765. */
  94766. get: function () {
  94767. return this._currentFrameRate;
  94768. },
  94769. enumerable: true,
  94770. configurable: true
  94771. });
  94772. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  94773. /**
  94774. * Gets or sets the current target frame rate (60 by default)
  94775. */
  94776. get: function () {
  94777. return this._targetFrameRate;
  94778. },
  94779. /**
  94780. * Gets or sets the current target frame rate (60 by default)
  94781. */
  94782. set: function (value) {
  94783. this._targetFrameRate = value;
  94784. },
  94785. enumerable: true,
  94786. configurable: true
  94787. });
  94788. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  94789. /**
  94790. * Gets or sets the current interval between two checks (every 2000ms by default)
  94791. */
  94792. get: function () {
  94793. return this._trackerDuration;
  94794. },
  94795. /**
  94796. * Gets or sets the current interval between two checks (every 2000ms by default)
  94797. */
  94798. set: function (value) {
  94799. this._trackerDuration = value;
  94800. },
  94801. enumerable: true,
  94802. configurable: true
  94803. });
  94804. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  94805. /**
  94806. * Gets the list of active optimizations
  94807. */
  94808. get: function () {
  94809. return this._options.optimizations;
  94810. },
  94811. enumerable: true,
  94812. configurable: true
  94813. });
  94814. /**
  94815. * Stops the current optimizer
  94816. */
  94817. SceneOptimizer.prototype.stop = function () {
  94818. this._isRunning = false;
  94819. };
  94820. /**
  94821. * Reset the optimizer to initial step (current priority level = 0)
  94822. */
  94823. SceneOptimizer.prototype.reset = function () {
  94824. this._currentPriorityLevel = 0;
  94825. };
  94826. /**
  94827. * Start the optimizer. By default it will try to reach a specific framerate
  94828. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  94829. */
  94830. SceneOptimizer.prototype.start = function () {
  94831. var _this = this;
  94832. if (this._isRunning) {
  94833. return;
  94834. }
  94835. this._isRunning = true;
  94836. // Let's wait for the scene to be ready before running our check
  94837. this._scene.executeWhenReady(function () {
  94838. setTimeout(function () {
  94839. _this._checkCurrentState();
  94840. }, _this._trackerDuration);
  94841. });
  94842. };
  94843. SceneOptimizer.prototype._checkCurrentState = function () {
  94844. var _this = this;
  94845. if (!this._isRunning) {
  94846. return;
  94847. }
  94848. var scene = this._scene;
  94849. var options = this._options;
  94850. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  94851. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  94852. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  94853. this._isRunning = false;
  94854. this.onSuccessObservable.notifyObservers(this);
  94855. return;
  94856. }
  94857. // Apply current level of optimizations
  94858. var allDone = true;
  94859. var noOptimizationApplied = true;
  94860. for (var index = 0; index < options.optimizations.length; index++) {
  94861. var optimization = options.optimizations[index];
  94862. if (optimization.priority === this._currentPriorityLevel) {
  94863. noOptimizationApplied = false;
  94864. allDone = allDone && optimization.apply(scene, this);
  94865. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  94866. }
  94867. }
  94868. // If no optimization was applied, this is a failure :(
  94869. if (noOptimizationApplied) {
  94870. this._isRunning = false;
  94871. this.onFailureObservable.notifyObservers(this);
  94872. return;
  94873. }
  94874. // If all optimizations were done, move to next level
  94875. if (allDone) {
  94876. this._currentPriorityLevel++;
  94877. }
  94878. // Let's the system running for a specific amount of time before checking FPS
  94879. scene.executeWhenReady(function () {
  94880. setTimeout(function () {
  94881. _this._checkCurrentState();
  94882. }, _this._trackerDuration);
  94883. });
  94884. };
  94885. /**
  94886. * Release all resources
  94887. */
  94888. SceneOptimizer.prototype.dispose = function () {
  94889. this.stop();
  94890. this.onSuccessObservable.clear();
  94891. this.onFailureObservable.clear();
  94892. this.onNewOptimizationAppliedObservable.clear();
  94893. if (this._sceneDisposeObserver) {
  94894. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94895. }
  94896. };
  94897. /**
  94898. * Helper function to create a SceneOptimizer with one single line of code
  94899. * @param scene defines the scene to work on
  94900. * @param options defines the options to use with the SceneOptimizer
  94901. * @param onSuccess defines a callback to call on success
  94902. * @param onFailure defines a callback to call on failure
  94903. * @returns the new SceneOptimizer object
  94904. */
  94905. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  94906. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  94907. if (onSuccess) {
  94908. optimizer.onSuccessObservable.add(function () {
  94909. onSuccess();
  94910. });
  94911. }
  94912. if (onFailure) {
  94913. optimizer.onFailureObservable.add(function () {
  94914. onFailure();
  94915. });
  94916. }
  94917. optimizer.start();
  94918. return optimizer;
  94919. };
  94920. return SceneOptimizer;
  94921. }());
  94922. BABYLON.SceneOptimizer = SceneOptimizer;
  94923. })(BABYLON || (BABYLON = {}));
  94924. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  94925. var BABYLON;
  94926. (function (BABYLON) {
  94927. var OutlineRenderer = /** @class */ (function () {
  94928. function OutlineRenderer(scene) {
  94929. this.zOffset = 1;
  94930. this._scene = scene;
  94931. }
  94932. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  94933. var _this = this;
  94934. if (useOverlay === void 0) { useOverlay = false; }
  94935. var scene = this._scene;
  94936. var engine = this._scene.getEngine();
  94937. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94938. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  94939. return;
  94940. }
  94941. var mesh = subMesh.getRenderingMesh();
  94942. var material = subMesh.getMaterial();
  94943. if (!material || !scene.activeCamera) {
  94944. return;
  94945. }
  94946. engine.enableEffect(this._effect);
  94947. // Logarithmic depth
  94948. if (material.useLogarithmicDepth) {
  94949. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  94950. }
  94951. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  94952. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  94953. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  94954. // Bones
  94955. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94956. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94957. }
  94958. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  94959. // Alpha test
  94960. if (material && material.needAlphaTesting()) {
  94961. var alphaTexture = material.getAlphaTestTexture();
  94962. if (alphaTexture) {
  94963. this._effect.setTexture("diffuseSampler", alphaTexture);
  94964. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  94965. }
  94966. }
  94967. engine.setZOffset(-this.zOffset);
  94968. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  94969. engine.setZOffset(0);
  94970. };
  94971. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  94972. var defines = [];
  94973. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  94974. var mesh = subMesh.getMesh();
  94975. var material = subMesh.getMaterial();
  94976. if (material) {
  94977. // Alpha test
  94978. if (material.needAlphaTesting()) {
  94979. defines.push("#define ALPHATEST");
  94980. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94981. attribs.push(BABYLON.VertexBuffer.UVKind);
  94982. defines.push("#define UV1");
  94983. }
  94984. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  94985. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94986. defines.push("#define UV2");
  94987. }
  94988. }
  94989. //Logarithmic depth
  94990. if (material.useLogarithmicDepth) {
  94991. defines.push("#define LOGARITHMICDEPTH");
  94992. }
  94993. }
  94994. // Bones
  94995. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94996. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94997. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94998. if (mesh.numBoneInfluencers > 4) {
  94999. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95000. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95001. }
  95002. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95003. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95004. }
  95005. else {
  95006. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95007. }
  95008. // Instances
  95009. if (useInstances) {
  95010. defines.push("#define INSTANCES");
  95011. attribs.push("world0");
  95012. attribs.push("world1");
  95013. attribs.push("world2");
  95014. attribs.push("world3");
  95015. }
  95016. // Get correct effect
  95017. var join = defines.join("\n");
  95018. if (this._cachedDefines !== join) {
  95019. this._cachedDefines = join;
  95020. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95021. }
  95022. return this._effect.isReady();
  95023. };
  95024. return OutlineRenderer;
  95025. }());
  95026. BABYLON.OutlineRenderer = OutlineRenderer;
  95027. })(BABYLON || (BABYLON = {}));
  95028. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95029. var BABYLON;
  95030. (function (BABYLON) {
  95031. var FaceAdjacencies = /** @class */ (function () {
  95032. function FaceAdjacencies() {
  95033. this.edges = new Array();
  95034. this.edgesConnectedCount = 0;
  95035. }
  95036. return FaceAdjacencies;
  95037. }());
  95038. var EdgesRenderer = /** @class */ (function () {
  95039. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95040. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95041. if (epsilon === void 0) { epsilon = 0.95; }
  95042. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95043. this.edgesWidthScalerForOrthographic = 1000.0;
  95044. this.edgesWidthScalerForPerspective = 50.0;
  95045. this._linesPositions = new Array();
  95046. this._linesNormals = new Array();
  95047. this._linesIndices = new Array();
  95048. this._buffers = {};
  95049. this._checkVerticesInsteadOfIndices = false;
  95050. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95051. this.isEnabled = true;
  95052. this._source = source;
  95053. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95054. this._epsilon = epsilon;
  95055. this._prepareRessources();
  95056. this._generateEdgesLines();
  95057. }
  95058. EdgesRenderer.prototype._prepareRessources = function () {
  95059. if (this._lineShader) {
  95060. return;
  95061. }
  95062. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95063. attributes: ["position", "normal"],
  95064. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95065. });
  95066. this._lineShader.disableDepthWrite = true;
  95067. this._lineShader.backFaceCulling = false;
  95068. };
  95069. EdgesRenderer.prototype._rebuild = function () {
  95070. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95071. if (buffer) {
  95072. buffer._rebuild();
  95073. }
  95074. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95075. if (buffer) {
  95076. buffer._rebuild();
  95077. }
  95078. var scene = this._source.getScene();
  95079. var engine = scene.getEngine();
  95080. this._ib = engine.createIndexBuffer(this._linesIndices);
  95081. };
  95082. EdgesRenderer.prototype.dispose = function () {
  95083. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95084. if (buffer) {
  95085. buffer.dispose();
  95086. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95087. }
  95088. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95089. if (buffer) {
  95090. buffer.dispose();
  95091. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95092. }
  95093. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95094. this._lineShader.dispose();
  95095. };
  95096. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95097. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95098. return 0;
  95099. }
  95100. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95101. return 1;
  95102. }
  95103. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95104. return 2;
  95105. }
  95106. return -1;
  95107. };
  95108. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  95109. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  95110. return 0;
  95111. }
  95112. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  95113. return 1;
  95114. }
  95115. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  95116. return 2;
  95117. }
  95118. return -1;
  95119. };
  95120. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  95121. var needToCreateLine;
  95122. if (edge === undefined) {
  95123. needToCreateLine = true;
  95124. }
  95125. else {
  95126. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  95127. needToCreateLine = dotProduct < this._epsilon;
  95128. }
  95129. if (needToCreateLine) {
  95130. var offset = this._linesPositions.length / 3;
  95131. var normal = p0.subtract(p1);
  95132. normal.normalize();
  95133. // Positions
  95134. this._linesPositions.push(p0.x);
  95135. this._linesPositions.push(p0.y);
  95136. this._linesPositions.push(p0.z);
  95137. this._linesPositions.push(p0.x);
  95138. this._linesPositions.push(p0.y);
  95139. this._linesPositions.push(p0.z);
  95140. this._linesPositions.push(p1.x);
  95141. this._linesPositions.push(p1.y);
  95142. this._linesPositions.push(p1.z);
  95143. this._linesPositions.push(p1.x);
  95144. this._linesPositions.push(p1.y);
  95145. this._linesPositions.push(p1.z);
  95146. // Normals
  95147. this._linesNormals.push(p1.x);
  95148. this._linesNormals.push(p1.y);
  95149. this._linesNormals.push(p1.z);
  95150. this._linesNormals.push(-1);
  95151. this._linesNormals.push(p1.x);
  95152. this._linesNormals.push(p1.y);
  95153. this._linesNormals.push(p1.z);
  95154. this._linesNormals.push(1);
  95155. this._linesNormals.push(p0.x);
  95156. this._linesNormals.push(p0.y);
  95157. this._linesNormals.push(p0.z);
  95158. this._linesNormals.push(-1);
  95159. this._linesNormals.push(p0.x);
  95160. this._linesNormals.push(p0.y);
  95161. this._linesNormals.push(p0.z);
  95162. this._linesNormals.push(1);
  95163. // Indices
  95164. this._linesIndices.push(offset);
  95165. this._linesIndices.push(offset + 1);
  95166. this._linesIndices.push(offset + 2);
  95167. this._linesIndices.push(offset);
  95168. this._linesIndices.push(offset + 2);
  95169. this._linesIndices.push(offset + 3);
  95170. }
  95171. };
  95172. EdgesRenderer.prototype._generateEdgesLines = function () {
  95173. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95174. var indices = this._source.getIndices();
  95175. if (!indices || !positions) {
  95176. return;
  95177. }
  95178. // First let's find adjacencies
  95179. var adjacencies = new Array();
  95180. var faceNormals = new Array();
  95181. var index;
  95182. var faceAdjacencies;
  95183. // Prepare faces
  95184. for (index = 0; index < indices.length; index += 3) {
  95185. faceAdjacencies = new FaceAdjacencies();
  95186. var p0Index = indices[index];
  95187. var p1Index = indices[index + 1];
  95188. var p2Index = indices[index + 2];
  95189. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  95190. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  95191. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  95192. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  95193. faceNormal.normalize();
  95194. faceNormals.push(faceNormal);
  95195. adjacencies.push(faceAdjacencies);
  95196. }
  95197. // Scan
  95198. for (index = 0; index < adjacencies.length; index++) {
  95199. faceAdjacencies = adjacencies[index];
  95200. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  95201. var otherFaceAdjacencies = adjacencies[otherIndex];
  95202. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  95203. break;
  95204. }
  95205. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  95206. continue;
  95207. }
  95208. var otherP0 = indices[otherIndex * 3];
  95209. var otherP1 = indices[otherIndex * 3 + 1];
  95210. var otherP2 = indices[otherIndex * 3 + 2];
  95211. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  95212. var otherEdgeIndex = 0;
  95213. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  95214. continue;
  95215. }
  95216. switch (edgeIndex) {
  95217. case 0:
  95218. if (this._checkVerticesInsteadOfIndices) {
  95219. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95220. }
  95221. else {
  95222. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  95223. }
  95224. break;
  95225. case 1:
  95226. if (this._checkVerticesInsteadOfIndices) {
  95227. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95228. }
  95229. else {
  95230. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  95231. }
  95232. break;
  95233. case 2:
  95234. if (this._checkVerticesInsteadOfIndices) {
  95235. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95236. }
  95237. else {
  95238. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  95239. }
  95240. break;
  95241. }
  95242. if (otherEdgeIndex === -1) {
  95243. continue;
  95244. }
  95245. faceAdjacencies.edges[edgeIndex] = otherIndex;
  95246. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  95247. faceAdjacencies.edgesConnectedCount++;
  95248. otherFaceAdjacencies.edgesConnectedCount++;
  95249. if (faceAdjacencies.edgesConnectedCount === 3) {
  95250. break;
  95251. }
  95252. }
  95253. }
  95254. }
  95255. // Create lines
  95256. for (index = 0; index < adjacencies.length; index++) {
  95257. // 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
  95258. var current = adjacencies[index];
  95259. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  95260. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  95261. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  95262. }
  95263. // Merge into a single mesh
  95264. var engine = this._source.getScene().getEngine();
  95265. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  95266. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  95267. this._ib = engine.createIndexBuffer(this._linesIndices);
  95268. this._indicesCount = this._linesIndices.length;
  95269. };
  95270. EdgesRenderer.prototype.render = function () {
  95271. var scene = this._source.getScene();
  95272. if (!this._lineShader.isReady() || !scene.activeCamera) {
  95273. return;
  95274. }
  95275. var engine = scene.getEngine();
  95276. this._lineShader._preBind();
  95277. // VBOs
  95278. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  95279. scene.resetCachedMaterial();
  95280. this._lineShader.setColor4("color", this._source.edgesColor);
  95281. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  95282. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  95283. }
  95284. else {
  95285. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  95286. }
  95287. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  95288. this._lineShader.bind(this._source.getWorldMatrix());
  95289. // Draw order
  95290. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  95291. this._lineShader.unbind();
  95292. engine.setDepthWrite(true);
  95293. };
  95294. return EdgesRenderer;
  95295. }());
  95296. BABYLON.EdgesRenderer = EdgesRenderer;
  95297. })(BABYLON || (BABYLON = {}));
  95298. //# sourceMappingURL=babylon.edgesRenderer.js.map
  95299. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95300. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95301. s = arguments[i];
  95302. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95303. t[p] = s[p];
  95304. }
  95305. return t;
  95306. };
  95307. var BABYLON;
  95308. (function (BABYLON) {
  95309. /**
  95310. * The effect layer Helps adding post process effect blended with the main pass.
  95311. *
  95312. * This can be for instance use to generate glow or higlight effects on the scene.
  95313. *
  95314. * The effect layer class can not be used directly and is intented to inherited from to be
  95315. * customized per effects.
  95316. */
  95317. var EffectLayer = /** @class */ (function () {
  95318. /**
  95319. * Instantiates a new effect Layer and references it in the scene.
  95320. * @param name The name of the layer
  95321. * @param scene The scene to use the layer in
  95322. */
  95323. function EffectLayer(
  95324. /** The Friendly of the effect in the scene */
  95325. name, scene) {
  95326. this._vertexBuffers = {};
  95327. this._maxSize = 0;
  95328. this._mainTextureDesiredSize = { width: 0, height: 0 };
  95329. this._shouldRender = true;
  95330. this._postProcesses = [];
  95331. this._textures = [];
  95332. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  95333. /**
  95334. * The clear color of the texture used to generate the glow map.
  95335. */
  95336. this.neutralColor = new BABYLON.Color4();
  95337. /**
  95338. * Specifies wether the highlight layer is enabled or not.
  95339. */
  95340. this.isEnabled = true;
  95341. /**
  95342. * An event triggered when the effect layer has been disposed.
  95343. */
  95344. this.onDisposeObservable = new BABYLON.Observable();
  95345. /**
  95346. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  95347. */
  95348. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  95349. /**
  95350. * An event triggered when the generated texture is being merged in the scene.
  95351. */
  95352. this.onBeforeComposeObservable = new BABYLON.Observable();
  95353. /**
  95354. * An event triggered when the generated texture has been merged in the scene.
  95355. */
  95356. this.onAfterComposeObservable = new BABYLON.Observable();
  95357. /**
  95358. * An event triggered when the efffect layer changes its size.
  95359. */
  95360. this.onSizeChangedObservable = new BABYLON.Observable();
  95361. this.name = name;
  95362. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95363. this._engine = scene.getEngine();
  95364. this._maxSize = this._engine.getCaps().maxTextureSize;
  95365. this._scene.effectLayers.push(this);
  95366. // Generate Buffers
  95367. this._generateIndexBuffer();
  95368. this._genrateVertexBuffer();
  95369. }
  95370. Object.defineProperty(EffectLayer.prototype, "camera", {
  95371. /**
  95372. * Gets the camera attached to the layer.
  95373. */
  95374. get: function () {
  95375. return this._effectLayerOptions.camera;
  95376. },
  95377. enumerable: true,
  95378. configurable: true
  95379. });
  95380. /**
  95381. * Initializes the effect layer with the required options.
  95382. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  95383. */
  95384. EffectLayer.prototype._init = function (options) {
  95385. // Adapt options
  95386. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95387. this._setMainTextureSize();
  95388. this._createMainTexture();
  95389. this._createTextureAndPostProcesses();
  95390. this._mergeEffect = this._createMergeEffect();
  95391. };
  95392. /**
  95393. * Generates the index buffer of the full screen quad blending to the main canvas.
  95394. */
  95395. EffectLayer.prototype._generateIndexBuffer = function () {
  95396. // Indices
  95397. var indices = [];
  95398. indices.push(0);
  95399. indices.push(1);
  95400. indices.push(2);
  95401. indices.push(0);
  95402. indices.push(2);
  95403. indices.push(3);
  95404. this._indexBuffer = this._engine.createIndexBuffer(indices);
  95405. };
  95406. /**
  95407. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  95408. */
  95409. EffectLayer.prototype._genrateVertexBuffer = function () {
  95410. // VBO
  95411. var vertices = [];
  95412. vertices.push(1, 1);
  95413. vertices.push(-1, 1);
  95414. vertices.push(-1, -1);
  95415. vertices.push(1, -1);
  95416. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95417. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95418. };
  95419. /**
  95420. * Sets the main texture desired size which is the closest power of two
  95421. * of the engine canvas size.
  95422. */
  95423. EffectLayer.prototype._setMainTextureSize = function () {
  95424. if (this._effectLayerOptions.mainTextureFixedSize) {
  95425. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  95426. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  95427. }
  95428. else {
  95429. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  95430. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  95431. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  95432. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  95433. }
  95434. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  95435. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  95436. };
  95437. /**
  95438. * Creates the main texture for the effect layer.
  95439. */
  95440. EffectLayer.prototype._createMainTexture = function () {
  95441. var _this = this;
  95442. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  95443. width: this._mainTextureDesiredSize.width,
  95444. height: this._mainTextureDesiredSize.height
  95445. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  95446. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  95447. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95448. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95449. this._mainTexture.anisotropicFilteringLevel = 1;
  95450. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95451. this._mainTexture.renderParticles = false;
  95452. this._mainTexture.renderList = null;
  95453. this._mainTexture.ignoreCameraViewport = true;
  95454. // Custom render function
  95455. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  95456. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  95457. var index;
  95458. var engine = _this._scene.getEngine();
  95459. if (depthOnlySubMeshes.length) {
  95460. engine.setColorWrite(false);
  95461. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  95462. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  95463. }
  95464. engine.setColorWrite(true);
  95465. }
  95466. for (index = 0; index < opaqueSubMeshes.length; index++) {
  95467. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  95468. }
  95469. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  95470. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  95471. }
  95472. for (index = 0; index < transparentSubMeshes.length; index++) {
  95473. _this._renderSubMesh(transparentSubMeshes.data[index]);
  95474. }
  95475. };
  95476. this._mainTexture.onClearObservable.add(function (engine) {
  95477. engine.clear(_this.neutralColor, true, true, true);
  95478. });
  95479. };
  95480. /**
  95481. * Checks for the readiness of the element composing the layer.
  95482. * @param subMesh the mesh to check for
  95483. * @param useInstances specify wether or not to use instances to render the mesh
  95484. * @param emissiveTexture the associated emissive texture used to generate the glow
  95485. * @return true if ready otherwise, false
  95486. */
  95487. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  95488. var material = subMesh.getMaterial();
  95489. if (!material) {
  95490. return false;
  95491. }
  95492. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  95493. return false;
  95494. }
  95495. var defines = [];
  95496. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95497. var mesh = subMesh.getMesh();
  95498. var uv1 = false;
  95499. var uv2 = false;
  95500. // Alpha test
  95501. if (material && material.needAlphaTesting()) {
  95502. var alphaTexture = material.getAlphaTestTexture();
  95503. if (alphaTexture) {
  95504. defines.push("#define ALPHATEST");
  95505. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95506. alphaTexture.coordinatesIndex === 1) {
  95507. defines.push("#define DIFFUSEUV2");
  95508. uv2 = true;
  95509. }
  95510. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95511. defines.push("#define DIFFUSEUV1");
  95512. uv1 = true;
  95513. }
  95514. }
  95515. }
  95516. // Emissive
  95517. if (emissiveTexture) {
  95518. defines.push("#define EMISSIVE");
  95519. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95520. emissiveTexture.coordinatesIndex === 1) {
  95521. defines.push("#define EMISSIVEUV2");
  95522. uv2 = true;
  95523. }
  95524. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95525. defines.push("#define EMISSIVEUV1");
  95526. uv1 = true;
  95527. }
  95528. }
  95529. if (uv1) {
  95530. attribs.push(BABYLON.VertexBuffer.UVKind);
  95531. defines.push("#define UV1");
  95532. }
  95533. if (uv2) {
  95534. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95535. defines.push("#define UV2");
  95536. }
  95537. // Bones
  95538. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95541. if (mesh.numBoneInfluencers > 4) {
  95542. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95543. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95544. }
  95545. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95546. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  95547. }
  95548. else {
  95549. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95550. }
  95551. // Morph targets
  95552. var manager = mesh.morphTargetManager;
  95553. var morphInfluencers = 0;
  95554. if (manager) {
  95555. if (manager.numInfluencers > 0) {
  95556. defines.push("#define MORPHTARGETS");
  95557. morphInfluencers = manager.numInfluencers;
  95558. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  95559. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  95560. }
  95561. }
  95562. // Instances
  95563. if (useInstances) {
  95564. defines.push("#define INSTANCES");
  95565. attribs.push("world0");
  95566. attribs.push("world1");
  95567. attribs.push("world2");
  95568. attribs.push("world3");
  95569. }
  95570. // Get correct effect
  95571. var join = defines.join("\n");
  95572. if (this._cachedDefines !== join) {
  95573. this._cachedDefines = join;
  95574. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  95575. }
  95576. return this._effectLayerMapGenerationEffect.isReady();
  95577. };
  95578. /**
  95579. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  95580. */
  95581. EffectLayer.prototype.render = function () {
  95582. var currentEffect = this._mergeEffect;
  95583. // Check
  95584. if (!currentEffect.isReady())
  95585. return;
  95586. for (var i = 0; i < this._postProcesses.length; i++) {
  95587. if (!this._postProcesses[i].isReady()) {
  95588. return;
  95589. }
  95590. }
  95591. var engine = this._scene.getEngine();
  95592. this.onBeforeComposeObservable.notifyObservers(this);
  95593. // Render
  95594. engine.enableEffect(currentEffect);
  95595. engine.setState(false);
  95596. // VBOs
  95597. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  95598. // Cache
  95599. var previousAlphaMode = engine.getAlphaMode();
  95600. // Go Blend.
  95601. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  95602. // Blends the map on the main canvas.
  95603. this._internalRender(currentEffect);
  95604. // Restore Alpha
  95605. engine.setAlphaMode(previousAlphaMode);
  95606. this.onAfterComposeObservable.notifyObservers(this);
  95607. // Handle size changes.
  95608. var size = this._mainTexture.getSize();
  95609. this._setMainTextureSize();
  95610. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  95611. // Recreate RTT and post processes on size change.
  95612. this.onSizeChangedObservable.notifyObservers(this);
  95613. this._disposeTextureAndPostProcesses();
  95614. this._createMainTexture();
  95615. this._createTextureAndPostProcesses();
  95616. }
  95617. };
  95618. /**
  95619. * Determine if a given mesh will be used in the current effect.
  95620. * @param mesh mesh to test
  95621. * @returns true if the mesh will be used
  95622. */
  95623. EffectLayer.prototype.hasMesh = function (mesh) {
  95624. return true;
  95625. };
  95626. /**
  95627. * Returns true if the layer contains information to display, otherwise false.
  95628. * @returns true if the glow layer should be rendered
  95629. */
  95630. EffectLayer.prototype.shouldRender = function () {
  95631. return this.isEnabled && this._shouldRender;
  95632. };
  95633. /**
  95634. * Returns true if the mesh should render, otherwise false.
  95635. * @param mesh The mesh to render
  95636. * @returns true if it should render otherwise false
  95637. */
  95638. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  95639. return true;
  95640. };
  95641. /**
  95642. * Returns true if the mesh should render, otherwise false.
  95643. * @param mesh The mesh to render
  95644. * @returns true if it should render otherwise false
  95645. */
  95646. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  95647. return true;
  95648. };
  95649. /**
  95650. * Renders the submesh passed in parameter to the generation map.
  95651. */
  95652. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  95653. var _this = this;
  95654. if (!this.shouldRender()) {
  95655. return;
  95656. }
  95657. var material = subMesh.getMaterial();
  95658. var mesh = subMesh.getRenderingMesh();
  95659. var scene = this._scene;
  95660. var engine = scene.getEngine();
  95661. if (!material) {
  95662. return;
  95663. }
  95664. // Do not block in blend mode.
  95665. if (material.needAlphaBlendingForMesh(mesh)) {
  95666. return;
  95667. }
  95668. // Culling
  95669. engine.setState(material.backFaceCulling);
  95670. // Managing instances
  95671. var batch = mesh._getInstancesRenderList(subMesh._id);
  95672. if (batch.mustReturn) {
  95673. return;
  95674. }
  95675. // Early Exit per mesh
  95676. if (!this._shouldRenderMesh(mesh)) {
  95677. return;
  95678. }
  95679. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95680. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  95681. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  95682. engine.enableEffect(this._effectLayerMapGenerationEffect);
  95683. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  95684. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  95685. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  95686. // Alpha test
  95687. if (material && material.needAlphaTesting()) {
  95688. var alphaTexture = material.getAlphaTestTexture();
  95689. if (alphaTexture) {
  95690. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  95691. var textureMatrix = alphaTexture.getTextureMatrix();
  95692. if (textureMatrix) {
  95693. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  95694. }
  95695. }
  95696. }
  95697. // Glow emissive only
  95698. if (this._emissiveTextureAndColor.texture) {
  95699. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  95700. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  95701. }
  95702. // Bones
  95703. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95704. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95705. }
  95706. // Morph targets
  95707. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  95708. // Draw
  95709. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  95710. }
  95711. else {
  95712. // Need to reset refresh rate of the shadowMap
  95713. this._mainTexture.resetRefreshCounter();
  95714. }
  95715. };
  95716. /**
  95717. * Rebuild the required buffers.
  95718. * @hidden Internal use only.
  95719. */
  95720. EffectLayer.prototype._rebuild = function () {
  95721. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95722. if (vb) {
  95723. vb._rebuild();
  95724. }
  95725. this._generateIndexBuffer();
  95726. };
  95727. /**
  95728. * Dispose only the render target textures and post process.
  95729. */
  95730. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  95731. this._mainTexture.dispose();
  95732. for (var i = 0; i < this._postProcesses.length; i++) {
  95733. if (this._postProcesses[i]) {
  95734. this._postProcesses[i].dispose();
  95735. }
  95736. }
  95737. this._postProcesses = [];
  95738. for (var i = 0; i < this._textures.length; i++) {
  95739. if (this._textures[i]) {
  95740. this._textures[i].dispose();
  95741. }
  95742. }
  95743. this._textures = [];
  95744. };
  95745. /**
  95746. * Dispose the highlight layer and free resources.
  95747. */
  95748. EffectLayer.prototype.dispose = function () {
  95749. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95750. if (vertexBuffer) {
  95751. vertexBuffer.dispose();
  95752. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95753. }
  95754. if (this._indexBuffer) {
  95755. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95756. this._indexBuffer = null;
  95757. }
  95758. // Clean textures and post processes
  95759. this._disposeTextureAndPostProcesses();
  95760. // Remove from scene
  95761. var index = this._scene.effectLayers.indexOf(this, 0);
  95762. if (index > -1) {
  95763. this._scene.effectLayers.splice(index, 1);
  95764. }
  95765. // Callback
  95766. this.onDisposeObservable.notifyObservers(this);
  95767. this.onDisposeObservable.clear();
  95768. this.onBeforeRenderMainTextureObservable.clear();
  95769. this.onBeforeComposeObservable.clear();
  95770. this.onAfterComposeObservable.clear();
  95771. this.onSizeChangedObservable.clear();
  95772. };
  95773. /**
  95774. * Gets the class name of the effect layer
  95775. * @returns the string with the class name of the effect layer
  95776. */
  95777. EffectLayer.prototype.getClassName = function () {
  95778. return "EffectLayer";
  95779. };
  95780. /**
  95781. * Creates an effect layer from parsed effect layer data
  95782. * @param parsedEffectLayer defines effect layer data
  95783. * @param scene defines the current scene
  95784. * @param rootUrl defines the root URL containing the effect layer information
  95785. * @returns a parsed effect Layer
  95786. */
  95787. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  95788. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  95789. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  95790. };
  95791. __decorate([
  95792. BABYLON.serialize()
  95793. ], EffectLayer.prototype, "name", void 0);
  95794. __decorate([
  95795. BABYLON.serializeAsColor4()
  95796. ], EffectLayer.prototype, "neutralColor", void 0);
  95797. __decorate([
  95798. BABYLON.serialize()
  95799. ], EffectLayer.prototype, "isEnabled", void 0);
  95800. __decorate([
  95801. BABYLON.serializeAsCameraReference()
  95802. ], EffectLayer.prototype, "camera", null);
  95803. return EffectLayer;
  95804. }());
  95805. BABYLON.EffectLayer = EffectLayer;
  95806. })(BABYLON || (BABYLON = {}));
  95807. //# sourceMappingURL=babylon.effectLayer.js.map
  95808. var BABYLON;
  95809. (function (BABYLON) {
  95810. /**
  95811. * Special Glow Blur post process only blurring the alpha channel
  95812. * It enforces keeping the most luminous color in the color channel.
  95813. */
  95814. var GlowBlurPostProcess = /** @class */ (function (_super) {
  95815. __extends(GlowBlurPostProcess, _super);
  95816. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  95817. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  95818. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  95819. _this.direction = direction;
  95820. _this.kernel = kernel;
  95821. _this.onApplyObservable.add(function (effect) {
  95822. effect.setFloat2("screenSize", _this.width, _this.height);
  95823. effect.setVector2("direction", _this.direction);
  95824. effect.setFloat("blurWidth", _this.kernel);
  95825. });
  95826. return _this;
  95827. }
  95828. return GlowBlurPostProcess;
  95829. }(BABYLON.PostProcess));
  95830. /**
  95831. * The highlight layer Helps adding a glow effect around a mesh.
  95832. *
  95833. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95834. * glowy meshes to your scene.
  95835. *
  95836. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  95837. */
  95838. var HighlightLayer = /** @class */ (function (_super) {
  95839. __extends(HighlightLayer, _super);
  95840. /**
  95841. * Instantiates a new highlight Layer and references it to the scene..
  95842. * @param name The name of the layer
  95843. * @param scene The scene to use the layer in
  95844. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  95845. */
  95846. function HighlightLayer(name, scene, options) {
  95847. var _this = _super.call(this, name, scene) || this;
  95848. _this.name = name;
  95849. /**
  95850. * Specifies whether or not the inner glow is ACTIVE in the layer.
  95851. */
  95852. _this.innerGlow = true;
  95853. /**
  95854. * Specifies whether or not the outer glow is ACTIVE in the layer.
  95855. */
  95856. _this.outerGlow = true;
  95857. /**
  95858. * An event triggered when the highlight layer is being blurred.
  95859. */
  95860. _this.onBeforeBlurObservable = new BABYLON.Observable();
  95861. /**
  95862. * An event triggered when the highlight layer has been blurred.
  95863. */
  95864. _this.onAfterBlurObservable = new BABYLON.Observable();
  95865. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  95866. _this._meshes = {};
  95867. _this._excludedMeshes = {};
  95868. _this.neutralColor = HighlightLayer.NeutralColor;
  95869. // Warn on stencil
  95870. if (!_this._engine.isStencilEnable) {
  95871. 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 }");
  95872. }
  95873. // Adapt options
  95874. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95875. // Initialize the layer
  95876. _this._init({
  95877. alphaBlendingMode: _this._options.alphaBlendingMode,
  95878. camera: _this._options.camera,
  95879. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95880. mainTextureRatio: _this._options.mainTextureRatio
  95881. });
  95882. // Do not render as long as no meshes have been added
  95883. _this._shouldRender = false;
  95884. return _this;
  95885. }
  95886. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  95887. /**
  95888. * Gets the horizontal size of the blur.
  95889. */
  95890. get: function () {
  95891. return this._horizontalBlurPostprocess.kernel;
  95892. },
  95893. /**
  95894. * Specifies the horizontal size of the blur.
  95895. */
  95896. set: function (value) {
  95897. this._horizontalBlurPostprocess.kernel = value;
  95898. },
  95899. enumerable: true,
  95900. configurable: true
  95901. });
  95902. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  95903. /**
  95904. * Gets the vertical size of the blur.
  95905. */
  95906. get: function () {
  95907. return this._verticalBlurPostprocess.kernel;
  95908. },
  95909. /**
  95910. * Specifies the vertical size of the blur.
  95911. */
  95912. set: function (value) {
  95913. this._verticalBlurPostprocess.kernel = value;
  95914. },
  95915. enumerable: true,
  95916. configurable: true
  95917. });
  95918. /**
  95919. * Get the effect name of the layer.
  95920. * @return The effect name
  95921. */
  95922. HighlightLayer.prototype.getEffectName = function () {
  95923. return HighlightLayer.EffectName;
  95924. };
  95925. /**
  95926. * Create the merge effect. This is the shader use to blit the information back
  95927. * to the main canvas at the end of the scene rendering.
  95928. */
  95929. HighlightLayer.prototype._createMergeEffect = function () {
  95930. // Effect
  95931. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  95932. };
  95933. /**
  95934. * Creates the render target textures and post processes used in the highlight layer.
  95935. */
  95936. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  95937. var _this = this;
  95938. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  95939. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  95940. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95941. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95942. var textureType = 0;
  95943. if (this._engine.getCaps().textureHalfFloatRender) {
  95944. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95945. }
  95946. else {
  95947. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95948. }
  95949. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  95950. width: blurTextureWidth,
  95951. height: blurTextureHeight
  95952. }, this._scene, false, true, textureType);
  95953. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95954. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95955. this._blurTexture.anisotropicFilteringLevel = 16;
  95956. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  95957. this._blurTexture.renderParticles = false;
  95958. this._blurTexture.ignoreCameraViewport = true;
  95959. this._textures = [this._blurTexture];
  95960. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  95961. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95962. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  95963. effect.setTexture("textureSampler", _this._mainTexture);
  95964. });
  95965. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95966. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95967. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95968. });
  95969. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95970. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  95971. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95972. });
  95973. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95974. }
  95975. else {
  95976. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  95977. width: blurTextureWidth,
  95978. height: blurTextureHeight
  95979. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95980. this._horizontalBlurPostprocess.width = blurTextureWidth;
  95981. this._horizontalBlurPostprocess.height = blurTextureHeight;
  95982. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95983. effect.setTexture("textureSampler", _this._mainTexture);
  95984. });
  95985. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  95986. width: blurTextureWidth,
  95987. height: blurTextureHeight
  95988. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95989. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95990. }
  95991. this._mainTexture.onAfterUnbindObservable.add(function () {
  95992. _this.onBeforeBlurObservable.notifyObservers(_this);
  95993. var internalTexture = _this._blurTexture.getInternalTexture();
  95994. if (internalTexture) {
  95995. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  95996. }
  95997. _this.onAfterBlurObservable.notifyObservers(_this);
  95998. });
  95999. // Prevent autoClear.
  96000. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96001. };
  96002. /**
  96003. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96004. */
  96005. HighlightLayer.prototype.needStencil = function () {
  96006. return true;
  96007. };
  96008. /**
  96009. * Checks for the readiness of the element composing the layer.
  96010. * @param subMesh the mesh to check for
  96011. * @param useInstances specify wether or not to use instances to render the mesh
  96012. * @param emissiveTexture the associated emissive texture used to generate the glow
  96013. * @return true if ready otherwise, false
  96014. */
  96015. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  96016. var material = subMesh.getMaterial();
  96017. var mesh = subMesh.getRenderingMesh();
  96018. if (!material || !mesh || !this._meshes) {
  96019. return false;
  96020. }
  96021. var emissiveTexture = null;
  96022. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96023. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96024. emissiveTexture = material.emissiveTexture;
  96025. }
  96026. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96027. };
  96028. /**
  96029. * Implementation specific of rendering the generating effect on the main canvas.
  96030. * @param effect The effect used to render through
  96031. */
  96032. HighlightLayer.prototype._internalRender = function (effect) {
  96033. // Texture
  96034. effect.setTexture("textureSampler", this._blurTexture);
  96035. // Cache
  96036. var engine = this._engine;
  96037. var previousStencilBuffer = engine.getStencilBuffer();
  96038. var previousStencilFunction = engine.getStencilFunction();
  96039. var previousStencilMask = engine.getStencilMask();
  96040. var previousStencilOperationPass = engine.getStencilOperationPass();
  96041. var previousStencilOperationFail = engine.getStencilOperationFail();
  96042. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  96043. var previousStencilReference = engine.getStencilFunctionReference();
  96044. // Stencil operations
  96045. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  96046. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  96047. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  96048. // Draw order
  96049. engine.setStencilMask(0x00);
  96050. engine.setStencilBuffer(true);
  96051. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  96052. // 2 passes inner outer
  96053. if (this.outerGlow) {
  96054. effect.setFloat("offset", 0);
  96055. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  96056. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96057. }
  96058. if (this.innerGlow) {
  96059. effect.setFloat("offset", 1);
  96060. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  96061. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96062. }
  96063. // Restore Cache
  96064. engine.setStencilFunction(previousStencilFunction);
  96065. engine.setStencilMask(previousStencilMask);
  96066. engine.setStencilBuffer(previousStencilBuffer);
  96067. engine.setStencilOperationPass(previousStencilOperationPass);
  96068. engine.setStencilOperationFail(previousStencilOperationFail);
  96069. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  96070. engine.setStencilFunctionReference(previousStencilReference);
  96071. };
  96072. /**
  96073. * Returns true if the layer contains information to display, otherwise false.
  96074. */
  96075. HighlightLayer.prototype.shouldRender = function () {
  96076. if (_super.prototype.shouldRender.call(this)) {
  96077. return this._meshes ? true : false;
  96078. }
  96079. return false;
  96080. };
  96081. /**
  96082. * Returns true if the mesh should render, otherwise false.
  96083. * @param mesh The mesh to render
  96084. * @returns true if it should render otherwise false
  96085. */
  96086. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  96087. // Excluded Mesh
  96088. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  96089. return false;
  96090. }
  96091. ;
  96092. return true;
  96093. };
  96094. /**
  96095. * Sets the required values for both the emissive texture and and the main color.
  96096. */
  96097. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96098. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96099. if (highlightLayerMesh) {
  96100. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  96101. }
  96102. else {
  96103. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96104. }
  96105. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96106. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96107. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  96108. }
  96109. else {
  96110. this._emissiveTextureAndColor.texture = null;
  96111. }
  96112. };
  96113. /**
  96114. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  96115. * @param mesh The mesh to exclude from the highlight layer
  96116. */
  96117. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  96118. if (!this._excludedMeshes) {
  96119. return;
  96120. }
  96121. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96122. if (!meshExcluded) {
  96123. this._excludedMeshes[mesh.uniqueId] = {
  96124. mesh: mesh,
  96125. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  96126. mesh.getEngine().setStencilBuffer(false);
  96127. }),
  96128. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  96129. mesh.getEngine().setStencilBuffer(true);
  96130. }),
  96131. };
  96132. }
  96133. };
  96134. /**
  96135. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  96136. * @param mesh The mesh to highlight
  96137. */
  96138. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  96139. if (!this._excludedMeshes) {
  96140. return;
  96141. }
  96142. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96143. if (meshExcluded) {
  96144. if (meshExcluded.beforeRender) {
  96145. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  96146. }
  96147. if (meshExcluded.afterRender) {
  96148. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  96149. }
  96150. }
  96151. this._excludedMeshes[mesh.uniqueId] = null;
  96152. };
  96153. /**
  96154. * Determine if a given mesh will be highlighted by the current HighlightLayer
  96155. * @param mesh mesh to test
  96156. * @returns true if the mesh will be highlighted by the current HighlightLayer
  96157. */
  96158. HighlightLayer.prototype.hasMesh = function (mesh) {
  96159. if (!this._meshes) {
  96160. return false;
  96161. }
  96162. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  96163. };
  96164. /**
  96165. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  96166. * @param mesh The mesh to highlight
  96167. * @param color The color of the highlight
  96168. * @param glowEmissiveOnly Extract the glow from the emissive texture
  96169. */
  96170. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  96171. var _this = this;
  96172. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  96173. if (!this._meshes) {
  96174. return;
  96175. }
  96176. var meshHighlight = this._meshes[mesh.uniqueId];
  96177. if (meshHighlight) {
  96178. meshHighlight.color = color;
  96179. }
  96180. else {
  96181. this._meshes[mesh.uniqueId] = {
  96182. mesh: mesh,
  96183. color: color,
  96184. // Lambda required for capture due to Observable this context
  96185. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  96186. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  96187. _this._defaultStencilReference(mesh);
  96188. }
  96189. else {
  96190. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  96191. }
  96192. }),
  96193. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  96194. glowEmissiveOnly: glowEmissiveOnly
  96195. };
  96196. }
  96197. this._shouldRender = true;
  96198. };
  96199. /**
  96200. * Remove a mesh from the highlight layer in order to make it stop glowing.
  96201. * @param mesh The mesh to highlight
  96202. */
  96203. HighlightLayer.prototype.removeMesh = function (mesh) {
  96204. if (!this._meshes) {
  96205. return;
  96206. }
  96207. var meshHighlight = this._meshes[mesh.uniqueId];
  96208. if (meshHighlight) {
  96209. if (meshHighlight.observerHighlight) {
  96210. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96211. }
  96212. if (meshHighlight.observerDefault) {
  96213. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96214. }
  96215. delete this._meshes[mesh.uniqueId];
  96216. }
  96217. this._shouldRender = false;
  96218. for (var meshHighlightToCheck in this._meshes) {
  96219. if (this._meshes[meshHighlightToCheck]) {
  96220. this._shouldRender = true;
  96221. break;
  96222. }
  96223. }
  96224. };
  96225. /**
  96226. * Force the stencil to the normal expected value for none glowing parts
  96227. */
  96228. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  96229. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  96230. };
  96231. /**
  96232. * Free any resources and references associated to a mesh.
  96233. * Internal use
  96234. * @param mesh The mesh to free.
  96235. */
  96236. HighlightLayer.prototype._disposeMesh = function (mesh) {
  96237. this.removeMesh(mesh);
  96238. this.removeExcludedMesh(mesh);
  96239. };
  96240. /**
  96241. * Dispose the highlight layer and free resources.
  96242. */
  96243. HighlightLayer.prototype.dispose = function () {
  96244. if (this._meshes) {
  96245. // Clean mesh references
  96246. for (var id in this._meshes) {
  96247. var meshHighlight = this._meshes[id];
  96248. if (meshHighlight && meshHighlight.mesh) {
  96249. if (meshHighlight.observerHighlight) {
  96250. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96251. }
  96252. if (meshHighlight.observerDefault) {
  96253. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96254. }
  96255. }
  96256. }
  96257. this._meshes = null;
  96258. }
  96259. if (this._excludedMeshes) {
  96260. for (var id in this._excludedMeshes) {
  96261. var meshHighlight = this._excludedMeshes[id];
  96262. if (meshHighlight) {
  96263. if (meshHighlight.beforeRender) {
  96264. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  96265. }
  96266. if (meshHighlight.afterRender) {
  96267. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  96268. }
  96269. }
  96270. }
  96271. this._excludedMeshes = null;
  96272. }
  96273. _super.prototype.dispose.call(this);
  96274. };
  96275. /**
  96276. * Gets the class name of the effect layer
  96277. * @returns the string with the class name of the effect layer
  96278. */
  96279. HighlightLayer.prototype.getClassName = function () {
  96280. return "HighlightLayer";
  96281. };
  96282. /**
  96283. * Serializes this Highlight layer
  96284. * @returns a serialized Highlight layer object
  96285. */
  96286. HighlightLayer.prototype.serialize = function () {
  96287. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96288. serializationObject.customType = "BABYLON.HighlightLayer";
  96289. // Highlighted meshes
  96290. serializationObject.meshes = [];
  96291. if (this._meshes) {
  96292. for (var m in this._meshes) {
  96293. var mesh = this._meshes[m];
  96294. if (mesh) {
  96295. serializationObject.meshes.push({
  96296. glowEmissiveOnly: mesh.glowEmissiveOnly,
  96297. color: mesh.color.asArray(),
  96298. meshId: mesh.mesh.id
  96299. });
  96300. }
  96301. }
  96302. }
  96303. // Excluded meshes
  96304. serializationObject.excludedMeshes = [];
  96305. if (this._excludedMeshes) {
  96306. for (var e in this._excludedMeshes) {
  96307. var excludedMesh = this._excludedMeshes[e];
  96308. if (excludedMesh) {
  96309. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  96310. }
  96311. }
  96312. }
  96313. return serializationObject;
  96314. };
  96315. /**
  96316. * Creates a Highlight layer from parsed Highlight layer data
  96317. * @param parsedHightlightLayer defines the Highlight layer data
  96318. * @param scene defines the current scene
  96319. * @param rootUrl defines the root URL containing the Highlight layer information
  96320. * @returns a parsed Highlight layer
  96321. */
  96322. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  96323. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  96324. var index;
  96325. // Excluded meshes
  96326. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  96327. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  96328. if (mesh) {
  96329. hl.addExcludedMesh(mesh);
  96330. }
  96331. }
  96332. // Included meshes
  96333. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  96334. var highlightedMesh = parsedHightlightLayer.meshes[index];
  96335. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  96336. if (mesh) {
  96337. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  96338. }
  96339. }
  96340. return hl;
  96341. };
  96342. /**
  96343. * Effect Name of the highlight layer.
  96344. */
  96345. HighlightLayer.EffectName = "HighlightLayer";
  96346. /**
  96347. * The neutral color used during the preparation of the glow effect.
  96348. * This is black by default as the blend operation is a blend operation.
  96349. */
  96350. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  96351. /**
  96352. * Stencil value used for glowing meshes.
  96353. */
  96354. HighlightLayer.GlowingMeshStencilReference = 0x02;
  96355. /**
  96356. * Stencil value used for the other meshes in the scene.
  96357. */
  96358. HighlightLayer.NormalMeshStencilReference = 0x01;
  96359. __decorate([
  96360. BABYLON.serialize()
  96361. ], HighlightLayer.prototype, "innerGlow", void 0);
  96362. __decorate([
  96363. BABYLON.serialize()
  96364. ], HighlightLayer.prototype, "outerGlow", void 0);
  96365. __decorate([
  96366. BABYLON.serialize()
  96367. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  96368. __decorate([
  96369. BABYLON.serialize()
  96370. ], HighlightLayer.prototype, "blurVerticalSize", null);
  96371. __decorate([
  96372. BABYLON.serialize("options")
  96373. ], HighlightLayer.prototype, "_options", void 0);
  96374. return HighlightLayer;
  96375. }(BABYLON.EffectLayer));
  96376. BABYLON.HighlightLayer = HighlightLayer;
  96377. })(BABYLON || (BABYLON = {}));
  96378. //# sourceMappingURL=babylon.highlightLayer.js.map
  96379. var BABYLON;
  96380. (function (BABYLON) {
  96381. /**
  96382. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  96383. *
  96384. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96385. * glowy meshes to your scene.
  96386. *
  96387. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  96388. */
  96389. var GlowLayer = /** @class */ (function (_super) {
  96390. __extends(GlowLayer, _super);
  96391. /**
  96392. * Instantiates a new glow Layer and references it to the scene.
  96393. * @param name The name of the layer
  96394. * @param scene The scene to use the layer in
  96395. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  96396. */
  96397. function GlowLayer(name, scene, options) {
  96398. var _this = _super.call(this, name, scene) || this;
  96399. _this._intensity = 1.0;
  96400. _this._includedOnlyMeshes = [];
  96401. _this._excludedMeshes = [];
  96402. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  96403. // Adapt options
  96404. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  96405. // Initialize the layer
  96406. _this._init({
  96407. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  96408. camera: _this._options.camera,
  96409. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96410. mainTextureRatio: _this._options.mainTextureRatio
  96411. });
  96412. return _this;
  96413. }
  96414. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  96415. /**
  96416. * Gets the kernel size of the blur.
  96417. */
  96418. get: function () {
  96419. return this._horizontalBlurPostprocess1.kernel;
  96420. },
  96421. /**
  96422. * Sets the kernel size of the blur.
  96423. */
  96424. set: function (value) {
  96425. this._horizontalBlurPostprocess1.kernel = value;
  96426. this._verticalBlurPostprocess1.kernel = value;
  96427. this._horizontalBlurPostprocess2.kernel = value;
  96428. this._verticalBlurPostprocess2.kernel = value;
  96429. },
  96430. enumerable: true,
  96431. configurable: true
  96432. });
  96433. Object.defineProperty(GlowLayer.prototype, "intensity", {
  96434. /**
  96435. * Gets the glow intensity.
  96436. */
  96437. get: function () {
  96438. return this._intensity;
  96439. },
  96440. /**
  96441. * Sets the glow intensity.
  96442. */
  96443. set: function (value) {
  96444. this._intensity = value;
  96445. },
  96446. enumerable: true,
  96447. configurable: true
  96448. });
  96449. /**
  96450. * Get the effect name of the layer.
  96451. * @return The effect name
  96452. */
  96453. GlowLayer.prototype.getEffectName = function () {
  96454. return GlowLayer.EffectName;
  96455. };
  96456. /**
  96457. * Create the merge effect. This is the shader use to blit the information back
  96458. * to the main canvas at the end of the scene rendering.
  96459. */
  96460. GlowLayer.prototype._createMergeEffect = function () {
  96461. // Effect
  96462. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  96463. };
  96464. /**
  96465. * Creates the render target textures and post processes used in the glow layer.
  96466. */
  96467. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  96468. var _this = this;
  96469. var blurTextureWidth = this._mainTextureDesiredSize.width;
  96470. var blurTextureHeight = this._mainTextureDesiredSize.height;
  96471. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96472. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96473. var textureType = 0;
  96474. if (this._engine.getCaps().textureHalfFloatRender) {
  96475. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96476. }
  96477. else {
  96478. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96479. }
  96480. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  96481. width: blurTextureWidth,
  96482. height: blurTextureHeight
  96483. }, this._scene, false, true, textureType);
  96484. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96485. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96486. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96487. this._blurTexture1.renderParticles = false;
  96488. this._blurTexture1.ignoreCameraViewport = true;
  96489. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  96490. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  96491. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  96492. width: blurTextureWidth2,
  96493. height: blurTextureHeight2
  96494. }, this._scene, false, true, textureType);
  96495. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96496. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96497. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96498. this._blurTexture2.renderParticles = false;
  96499. this._blurTexture2.ignoreCameraViewport = true;
  96500. this._textures = [this._blurTexture1, this._blurTexture2];
  96501. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96502. width: blurTextureWidth,
  96503. height: blurTextureHeight
  96504. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96505. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  96506. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  96507. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  96508. effect.setTexture("textureSampler", _this._mainTexture);
  96509. });
  96510. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96511. width: blurTextureWidth,
  96512. height: blurTextureHeight
  96513. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96514. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96515. width: blurTextureWidth2,
  96516. height: blurTextureHeight2
  96517. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96518. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  96519. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  96520. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  96521. effect.setTexture("textureSampler", _this._blurTexture1);
  96522. });
  96523. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96524. width: blurTextureWidth2,
  96525. height: blurTextureHeight2
  96526. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96527. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96528. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  96529. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96530. this._mainTexture.samples = this._options.mainTextureSamples;
  96531. this._mainTexture.onAfterUnbindObservable.add(function () {
  96532. var internalTexture = _this._blurTexture1.getInternalTexture();
  96533. if (internalTexture) {
  96534. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  96535. internalTexture = _this._blurTexture2.getInternalTexture();
  96536. if (internalTexture) {
  96537. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  96538. }
  96539. }
  96540. });
  96541. // Prevent autoClear.
  96542. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96543. };
  96544. /**
  96545. * Checks for the readiness of the element composing the layer.
  96546. * @param subMesh the mesh to check for
  96547. * @param useInstances specify wether or not to use instances to render the mesh
  96548. * @param emissiveTexture the associated emissive texture used to generate the glow
  96549. * @return true if ready otherwise, false
  96550. */
  96551. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  96552. var material = subMesh.getMaterial();
  96553. var mesh = subMesh.getRenderingMesh();
  96554. if (!material || !mesh) {
  96555. return false;
  96556. }
  96557. var emissiveTexture = material.emissiveTexture;
  96558. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96559. };
  96560. /**
  96561. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96562. */
  96563. GlowLayer.prototype.needStencil = function () {
  96564. return false;
  96565. };
  96566. /**
  96567. * Implementation specific of rendering the generating effect on the main canvas.
  96568. * @param effect The effect used to render through
  96569. */
  96570. GlowLayer.prototype._internalRender = function (effect) {
  96571. // Texture
  96572. effect.setTexture("textureSampler", this._blurTexture1);
  96573. effect.setTexture("textureSampler2", this._blurTexture2);
  96574. effect.setFloat("offset", this._intensity);
  96575. // Cache
  96576. var engine = this._engine;
  96577. var previousStencilBuffer = engine.getStencilBuffer();
  96578. // Draw order
  96579. engine.setStencilBuffer(false);
  96580. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96581. // Draw order
  96582. engine.setStencilBuffer(previousStencilBuffer);
  96583. };
  96584. /**
  96585. * Sets the required values for both the emissive texture and and the main color.
  96586. */
  96587. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96588. var textureLevel = 1.0;
  96589. if (this.customEmissiveTextureSelector) {
  96590. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  96591. }
  96592. else {
  96593. if (material) {
  96594. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96595. if (this._emissiveTextureAndColor.texture) {
  96596. textureLevel = this._emissiveTextureAndColor.texture.level;
  96597. }
  96598. }
  96599. else {
  96600. this._emissiveTextureAndColor.texture = null;
  96601. }
  96602. }
  96603. if (this.customEmissiveColorSelector) {
  96604. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  96605. }
  96606. else {
  96607. if (material.emissiveColor) {
  96608. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  96609. }
  96610. else {
  96611. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96612. }
  96613. }
  96614. };
  96615. /**
  96616. * Returns true if the mesh should render, otherwise false.
  96617. * @param mesh The mesh to render
  96618. * @returns true if it should render otherwise false
  96619. */
  96620. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  96621. return this.hasMesh(mesh);
  96622. };
  96623. /**
  96624. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  96625. * @param mesh The mesh to exclude from the glow layer
  96626. */
  96627. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  96628. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  96629. this._excludedMeshes.push(mesh.uniqueId);
  96630. }
  96631. };
  96632. /**
  96633. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  96634. * @param mesh The mesh to remove
  96635. */
  96636. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  96637. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  96638. if (index !== -1) {
  96639. this._excludedMeshes.splice(index, 1);
  96640. }
  96641. };
  96642. /**
  96643. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  96644. * @param mesh The mesh to include in the glow layer
  96645. */
  96646. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  96647. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  96648. this._includedOnlyMeshes.push(mesh.uniqueId);
  96649. }
  96650. };
  96651. /**
  96652. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  96653. * @param mesh The mesh to remove
  96654. */
  96655. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  96656. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  96657. if (index !== -1) {
  96658. this._includedOnlyMeshes.splice(index, 1);
  96659. }
  96660. };
  96661. /**
  96662. * Determine if a given mesh will be used in the glow layer
  96663. * @param mesh The mesh to test
  96664. * @returns true if the mesh will be highlighted by the current glow layer
  96665. */
  96666. GlowLayer.prototype.hasMesh = function (mesh) {
  96667. // Included Mesh
  96668. if (this._includedOnlyMeshes.length) {
  96669. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  96670. }
  96671. ;
  96672. // Excluded Mesh
  96673. if (this._excludedMeshes.length) {
  96674. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  96675. }
  96676. ;
  96677. return true;
  96678. };
  96679. /**
  96680. * Free any resources and references associated to a mesh.
  96681. * Internal use
  96682. * @param mesh The mesh to free.
  96683. */
  96684. GlowLayer.prototype._disposeMesh = function (mesh) {
  96685. this.removeIncludedOnlyMesh(mesh);
  96686. this.removeExcludedMesh(mesh);
  96687. };
  96688. /**
  96689. * Gets the class name of the effect layer
  96690. * @returns the string with the class name of the effect layer
  96691. */
  96692. GlowLayer.prototype.getClassName = function () {
  96693. return "GlowLayer";
  96694. };
  96695. /**
  96696. * Serializes this glow layer
  96697. * @returns a serialized glow layer object
  96698. */
  96699. GlowLayer.prototype.serialize = function () {
  96700. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96701. serializationObject.customType = "BABYLON.GlowLayer";
  96702. var index;
  96703. // Included meshes
  96704. serializationObject.includedMeshes = [];
  96705. if (this._includedOnlyMeshes.length) {
  96706. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  96707. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  96708. if (mesh) {
  96709. serializationObject.includedMeshes.push(mesh.id);
  96710. }
  96711. }
  96712. }
  96713. // Excluded meshes
  96714. serializationObject.excludedMeshes = [];
  96715. if (this._excludedMeshes.length) {
  96716. for (index = 0; index < this._excludedMeshes.length; index++) {
  96717. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  96718. if (mesh) {
  96719. serializationObject.excludedMeshes.push(mesh.id);
  96720. }
  96721. }
  96722. }
  96723. return serializationObject;
  96724. };
  96725. /**
  96726. * Creates a Glow Layer from parsed glow layer data
  96727. * @param parsedGlowLayer defines glow layer data
  96728. * @param scene defines the current scene
  96729. * @param rootUrl defines the root URL containing the glow layer information
  96730. * @returns a parsed Glow Layer
  96731. */
  96732. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  96733. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  96734. var index;
  96735. // Excluded meshes
  96736. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  96737. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  96738. if (mesh) {
  96739. gl.addExcludedMesh(mesh);
  96740. }
  96741. }
  96742. // Included meshes
  96743. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  96744. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  96745. if (mesh) {
  96746. gl.addIncludedOnlyMesh(mesh);
  96747. }
  96748. }
  96749. return gl;
  96750. };
  96751. /**
  96752. * Effect Name of the layer.
  96753. */
  96754. GlowLayer.EffectName = "GlowLayer";
  96755. /**
  96756. * The default blur kernel size used for the glow.
  96757. */
  96758. GlowLayer.DefaultBlurKernelSize = 32;
  96759. /**
  96760. * The default texture size ratio used for the glow.
  96761. */
  96762. GlowLayer.DefaultTextureRatio = 0.5;
  96763. __decorate([
  96764. BABYLON.serialize()
  96765. ], GlowLayer.prototype, "blurKernelSize", null);
  96766. __decorate([
  96767. BABYLON.serialize()
  96768. ], GlowLayer.prototype, "intensity", null);
  96769. __decorate([
  96770. BABYLON.serialize("options")
  96771. ], GlowLayer.prototype, "_options", void 0);
  96772. return GlowLayer;
  96773. }(BABYLON.EffectLayer));
  96774. BABYLON.GlowLayer = GlowLayer;
  96775. })(BABYLON || (BABYLON = {}));
  96776. //# sourceMappingURL=babylon.glowLayer.js.map
  96777. var BABYLON;
  96778. (function (BABYLON) {
  96779. /**
  96780. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  96781. */
  96782. var AssetTaskState;
  96783. (function (AssetTaskState) {
  96784. /**
  96785. * Initialization
  96786. */
  96787. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  96788. /**
  96789. * Running
  96790. */
  96791. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  96792. /**
  96793. * Done
  96794. */
  96795. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  96796. /**
  96797. * Error
  96798. */
  96799. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  96800. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  96801. /**
  96802. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  96803. */
  96804. var AbstractAssetTask = /** @class */ (function () {
  96805. /**
  96806. * Creates a new {BABYLON.AssetsManager}
  96807. * @param name defines the name of the task
  96808. */
  96809. function AbstractAssetTask(
  96810. /**
  96811. * Task name
  96812. */ name) {
  96813. this.name = name;
  96814. this._isCompleted = false;
  96815. this._taskState = AssetTaskState.INIT;
  96816. }
  96817. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  96818. /**
  96819. * Get if the task is completed
  96820. */
  96821. get: function () {
  96822. return this._isCompleted;
  96823. },
  96824. enumerable: true,
  96825. configurable: true
  96826. });
  96827. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  96828. /**
  96829. * Gets the current state of the task
  96830. */
  96831. get: function () {
  96832. return this._taskState;
  96833. },
  96834. enumerable: true,
  96835. configurable: true
  96836. });
  96837. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  96838. /**
  96839. * Gets the current error object (if task is in error)
  96840. */
  96841. get: function () {
  96842. return this._errorObject;
  96843. },
  96844. enumerable: true,
  96845. configurable: true
  96846. });
  96847. /**
  96848. * Internal only
  96849. * @hidden
  96850. */
  96851. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  96852. if (this._errorObject) {
  96853. return;
  96854. }
  96855. this._errorObject = {
  96856. message: message,
  96857. exception: exception
  96858. };
  96859. };
  96860. /**
  96861. * Execute the current task
  96862. * @param scene defines the scene where you want your assets to be loaded
  96863. * @param onSuccess is a callback called when the task is successfully executed
  96864. * @param onError is a callback called if an error occurs
  96865. */
  96866. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96867. var _this = this;
  96868. this._taskState = AssetTaskState.RUNNING;
  96869. this.runTask(scene, function () {
  96870. _this.onDoneCallback(onSuccess, onError);
  96871. }, function (msg, exception) {
  96872. _this.onErrorCallback(onError, msg, exception);
  96873. });
  96874. };
  96875. /**
  96876. * Execute the current task
  96877. * @param scene defines the scene where you want your assets to be loaded
  96878. * @param onSuccess is a callback called when the task is successfully executed
  96879. * @param onError is a callback called if an error occurs
  96880. */
  96881. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96882. throw new Error("runTask is not implemented");
  96883. };
  96884. /**
  96885. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  96886. * This can be used with failed tasks that have the reason for failure fixed.
  96887. */
  96888. AbstractAssetTask.prototype.reset = function () {
  96889. this._taskState = AssetTaskState.INIT;
  96890. };
  96891. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  96892. this._taskState = AssetTaskState.ERROR;
  96893. this._errorObject = {
  96894. message: message,
  96895. exception: exception
  96896. };
  96897. if (this.onError) {
  96898. this.onError(this, message, exception);
  96899. }
  96900. onError();
  96901. };
  96902. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  96903. try {
  96904. this._taskState = AssetTaskState.DONE;
  96905. this._isCompleted = true;
  96906. if (this.onSuccess) {
  96907. this.onSuccess(this);
  96908. }
  96909. onSuccess();
  96910. }
  96911. catch (e) {
  96912. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  96913. }
  96914. };
  96915. return AbstractAssetTask;
  96916. }());
  96917. BABYLON.AbstractAssetTask = AbstractAssetTask;
  96918. /**
  96919. * Class used to share progress information about assets loading
  96920. */
  96921. var AssetsProgressEvent = /** @class */ (function () {
  96922. /**
  96923. * Creates a {BABYLON.AssetsProgressEvent}
  96924. * @param remainingCount defines the number of remaining tasks to process
  96925. * @param totalCount defines the total number of tasks
  96926. * @param task defines the task that was just processed
  96927. */
  96928. function AssetsProgressEvent(remainingCount, totalCount, task) {
  96929. this.remainingCount = remainingCount;
  96930. this.totalCount = totalCount;
  96931. this.task = task;
  96932. }
  96933. return AssetsProgressEvent;
  96934. }());
  96935. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  96936. /**
  96937. * Define a task used by {BABYLON.AssetsManager} to load meshes
  96938. */
  96939. var MeshAssetTask = /** @class */ (function (_super) {
  96940. __extends(MeshAssetTask, _super);
  96941. /**
  96942. * Creates a new {BABYLON.MeshAssetTask}
  96943. * @param name defines the name of the task
  96944. * @param meshesNames defines the list of mesh's names you want to load
  96945. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  96946. * @param sceneFilename defines the filename of the scene to load from
  96947. */
  96948. function MeshAssetTask(
  96949. /**
  96950. * Defines the name of the task
  96951. */
  96952. name,
  96953. /**
  96954. * Defines the list of mesh's names you want to load
  96955. */
  96956. meshesNames,
  96957. /**
  96958. * Defines the root url to use as a base to load your meshes and associated resources
  96959. */
  96960. rootUrl,
  96961. /**
  96962. * Defines the filename of the scene to load from
  96963. */
  96964. sceneFilename) {
  96965. var _this = _super.call(this, name) || this;
  96966. _this.name = name;
  96967. _this.meshesNames = meshesNames;
  96968. _this.rootUrl = rootUrl;
  96969. _this.sceneFilename = sceneFilename;
  96970. return _this;
  96971. }
  96972. /**
  96973. * Execute the current task
  96974. * @param scene defines the scene where you want your assets to be loaded
  96975. * @param onSuccess is a callback called when the task is successfully executed
  96976. * @param onError is a callback called if an error occurs
  96977. */
  96978. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96979. var _this = this;
  96980. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  96981. _this.loadedMeshes = meshes;
  96982. _this.loadedParticleSystems = particleSystems;
  96983. _this.loadedSkeletons = skeletons;
  96984. onSuccess();
  96985. }, null, function (scene, message, exception) {
  96986. onError(message, exception);
  96987. });
  96988. };
  96989. return MeshAssetTask;
  96990. }(AbstractAssetTask));
  96991. BABYLON.MeshAssetTask = MeshAssetTask;
  96992. /**
  96993. * Define a task used by {BABYLON.AssetsManager} to load text content
  96994. */
  96995. var TextFileAssetTask = /** @class */ (function (_super) {
  96996. __extends(TextFileAssetTask, _super);
  96997. /**
  96998. * Creates a new TextFileAssetTask object
  96999. * @param name defines the name of the task
  97000. * @param url defines the location of the file to load
  97001. */
  97002. function TextFileAssetTask(
  97003. /**
  97004. * Defines the name of the task
  97005. */
  97006. name,
  97007. /**
  97008. * Defines the location of the file to load
  97009. */
  97010. url) {
  97011. var _this = _super.call(this, name) || this;
  97012. _this.name = name;
  97013. _this.url = url;
  97014. return _this;
  97015. }
  97016. /**
  97017. * Execute the current task
  97018. * @param scene defines the scene where you want your assets to be loaded
  97019. * @param onSuccess is a callback called when the task is successfully executed
  97020. * @param onError is a callback called if an error occurs
  97021. */
  97022. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97023. var _this = this;
  97024. scene._loadFile(this.url, function (data) {
  97025. _this.text = data;
  97026. onSuccess();
  97027. }, undefined, false, false, function (request, exception) {
  97028. if (request) {
  97029. onError(request.status + " " + request.statusText, exception);
  97030. }
  97031. });
  97032. };
  97033. return TextFileAssetTask;
  97034. }(AbstractAssetTask));
  97035. BABYLON.TextFileAssetTask = TextFileAssetTask;
  97036. /**
  97037. * Define a task used by {BABYLON.AssetsManager} to load binary data
  97038. */
  97039. var BinaryFileAssetTask = /** @class */ (function (_super) {
  97040. __extends(BinaryFileAssetTask, _super);
  97041. /**
  97042. * Creates a new BinaryFileAssetTask object
  97043. * @param name defines the name of the new task
  97044. * @param url defines the location of the file to load
  97045. */
  97046. function BinaryFileAssetTask(
  97047. /**
  97048. * Defines the name of the task
  97049. */
  97050. name,
  97051. /**
  97052. * Defines the location of the file to load
  97053. */
  97054. url) {
  97055. var _this = _super.call(this, name) || this;
  97056. _this.name = name;
  97057. _this.url = url;
  97058. return _this;
  97059. }
  97060. /**
  97061. * Execute the current task
  97062. * @param scene defines the scene where you want your assets to be loaded
  97063. * @param onSuccess is a callback called when the task is successfully executed
  97064. * @param onError is a callback called if an error occurs
  97065. */
  97066. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97067. var _this = this;
  97068. scene._loadFile(this.url, function (data) {
  97069. _this.data = data;
  97070. onSuccess();
  97071. }, undefined, true, true, function (request, exception) {
  97072. if (request) {
  97073. onError(request.status + " " + request.statusText, exception);
  97074. }
  97075. });
  97076. };
  97077. return BinaryFileAssetTask;
  97078. }(AbstractAssetTask));
  97079. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  97080. /**
  97081. * Define a task used by {BABYLON.AssetsManager} to load images
  97082. */
  97083. var ImageAssetTask = /** @class */ (function (_super) {
  97084. __extends(ImageAssetTask, _super);
  97085. /**
  97086. * Creates a new ImageAssetTask
  97087. * @param name defines the name of the task
  97088. * @param url defines the location of the image to load
  97089. */
  97090. function ImageAssetTask(
  97091. /**
  97092. * Defines the name of the task
  97093. */
  97094. name,
  97095. /**
  97096. * Defines the location of the image to load
  97097. */
  97098. url) {
  97099. var _this = _super.call(this, name) || this;
  97100. _this.name = name;
  97101. _this.url = url;
  97102. return _this;
  97103. }
  97104. /**
  97105. * Execute the current task
  97106. * @param scene defines the scene where you want your assets to be loaded
  97107. * @param onSuccess is a callback called when the task is successfully executed
  97108. * @param onError is a callback called if an error occurs
  97109. */
  97110. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97111. var _this = this;
  97112. var img = new Image();
  97113. BABYLON.Tools.SetCorsBehavior(this.url, img);
  97114. img.onload = function () {
  97115. _this.image = img;
  97116. onSuccess();
  97117. };
  97118. img.onerror = function (err) {
  97119. onError("Error loading image", err);
  97120. };
  97121. img.src = this.url;
  97122. };
  97123. return ImageAssetTask;
  97124. }(AbstractAssetTask));
  97125. BABYLON.ImageAssetTask = ImageAssetTask;
  97126. /**
  97127. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  97128. */
  97129. var TextureAssetTask = /** @class */ (function (_super) {
  97130. __extends(TextureAssetTask, _super);
  97131. /**
  97132. * Creates a new TextureAssetTask object
  97133. * @param name defines the name of the task
  97134. * @param url defines the location of the file to load
  97135. * @param noMipmap defines if mipmap should not be generated (default is false)
  97136. * @param invertY defines if texture must be inverted on Y axis (default is false)
  97137. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97138. */
  97139. function TextureAssetTask(
  97140. /**
  97141. * Defines the name of the task
  97142. */
  97143. name,
  97144. /**
  97145. * Defines the location of the file to load
  97146. */
  97147. url,
  97148. /**
  97149. * Defines if mipmap should not be generated (default is false)
  97150. */
  97151. noMipmap,
  97152. /**
  97153. * Defines if texture must be inverted on Y axis (default is false)
  97154. */
  97155. invertY,
  97156. /**
  97157. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97158. */
  97159. samplingMode) {
  97160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97161. var _this = _super.call(this, name) || this;
  97162. _this.name = name;
  97163. _this.url = url;
  97164. _this.noMipmap = noMipmap;
  97165. _this.invertY = invertY;
  97166. _this.samplingMode = samplingMode;
  97167. return _this;
  97168. }
  97169. /**
  97170. * Execute the current task
  97171. * @param scene defines the scene where you want your assets to be loaded
  97172. * @param onSuccess is a callback called when the task is successfully executed
  97173. * @param onError is a callback called if an error occurs
  97174. */
  97175. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97176. var onload = function () {
  97177. onSuccess();
  97178. };
  97179. var onerror = function (message, exception) {
  97180. onError(message, exception);
  97181. };
  97182. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  97183. };
  97184. return TextureAssetTask;
  97185. }(AbstractAssetTask));
  97186. BABYLON.TextureAssetTask = TextureAssetTask;
  97187. /**
  97188. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  97189. */
  97190. var CubeTextureAssetTask = /** @class */ (function (_super) {
  97191. __extends(CubeTextureAssetTask, _super);
  97192. /**
  97193. * Creates a new CubeTextureAssetTask
  97194. * @param name defines the name of the task
  97195. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97196. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97197. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97198. * @param files defines the explicit list of files (undefined by default)
  97199. */
  97200. function CubeTextureAssetTask(
  97201. /**
  97202. * Defines the name of the task
  97203. */
  97204. name,
  97205. /**
  97206. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97207. */
  97208. url,
  97209. /**
  97210. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97211. */
  97212. extensions,
  97213. /**
  97214. * Defines if mipmaps should not be generated (default is false)
  97215. */
  97216. noMipmap,
  97217. /**
  97218. * Defines the explicit list of files (undefined by default)
  97219. */
  97220. files) {
  97221. var _this = _super.call(this, name) || this;
  97222. _this.name = name;
  97223. _this.url = url;
  97224. _this.extensions = extensions;
  97225. _this.noMipmap = noMipmap;
  97226. _this.files = files;
  97227. return _this;
  97228. }
  97229. /**
  97230. * Execute the current task
  97231. * @param scene defines the scene where you want your assets to be loaded
  97232. * @param onSuccess is a callback called when the task is successfully executed
  97233. * @param onError is a callback called if an error occurs
  97234. */
  97235. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97236. var onload = function () {
  97237. onSuccess();
  97238. };
  97239. var onerror = function (message, exception) {
  97240. onError(message, exception);
  97241. };
  97242. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  97243. };
  97244. return CubeTextureAssetTask;
  97245. }(AbstractAssetTask));
  97246. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  97247. /**
  97248. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  97249. */
  97250. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  97251. __extends(HDRCubeTextureAssetTask, _super);
  97252. /**
  97253. * Creates a new HDRCubeTextureAssetTask object
  97254. * @param name defines the name of the task
  97255. * @param url defines the location of the file to load
  97256. * @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.
  97257. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97258. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97259. * @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)
  97260. * @param reserved Internal use only
  97261. */
  97262. function HDRCubeTextureAssetTask(
  97263. /**
  97264. * Defines the name of the task
  97265. */
  97266. name,
  97267. /**
  97268. * Defines the location of the file to load
  97269. */
  97270. url,
  97271. /**
  97272. * Defines the desired size (the more it increases the longer the generation will be)
  97273. */
  97274. size,
  97275. /**
  97276. * Defines if mipmaps should not be generated (default is false)
  97277. */
  97278. noMipmap,
  97279. /**
  97280. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97281. */
  97282. generateHarmonics,
  97283. /**
  97284. * 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)
  97285. */
  97286. gammaSpace,
  97287. /**
  97288. * Internal Use Only
  97289. */
  97290. reserved) {
  97291. if (noMipmap === void 0) { noMipmap = false; }
  97292. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97293. if (gammaSpace === void 0) { gammaSpace = false; }
  97294. if (reserved === void 0) { reserved = false; }
  97295. var _this = _super.call(this, name) || this;
  97296. _this.name = name;
  97297. _this.url = url;
  97298. _this.size = size;
  97299. _this.noMipmap = noMipmap;
  97300. _this.generateHarmonics = generateHarmonics;
  97301. _this.gammaSpace = gammaSpace;
  97302. _this.reserved = reserved;
  97303. return _this;
  97304. }
  97305. /**
  97306. * Execute the current task
  97307. * @param scene defines the scene where you want your assets to be loaded
  97308. * @param onSuccess is a callback called when the task is successfully executed
  97309. * @param onError is a callback called if an error occurs
  97310. */
  97311. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97312. var onload = function () {
  97313. onSuccess();
  97314. };
  97315. var onerror = function (message, exception) {
  97316. onError(message, exception);
  97317. };
  97318. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  97319. };
  97320. return HDRCubeTextureAssetTask;
  97321. }(AbstractAssetTask));
  97322. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  97323. /**
  97324. * This class can be used to easily import assets into a scene
  97325. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  97326. */
  97327. var AssetsManager = /** @class */ (function () {
  97328. /**
  97329. * Creates a new AssetsManager
  97330. * @param scene defines the scene to work on
  97331. */
  97332. function AssetsManager(scene) {
  97333. this._isLoading = false;
  97334. this._tasks = new Array();
  97335. this._waitingTasksCount = 0;
  97336. this._totalTasksCount = 0;
  97337. /**
  97338. * Observable called when all tasks are processed
  97339. */
  97340. this.onTaskSuccessObservable = new BABYLON.Observable();
  97341. /**
  97342. * Observable called when a task had an error
  97343. */
  97344. this.onTaskErrorObservable = new BABYLON.Observable();
  97345. /**
  97346. * Observable called when a task is successful
  97347. */
  97348. this.onTasksDoneObservable = new BABYLON.Observable();
  97349. /**
  97350. * Observable called when a task is done (whatever the result is)
  97351. */
  97352. this.onProgressObservable = new BABYLON.Observable();
  97353. /**
  97354. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  97355. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  97356. */
  97357. this.useDefaultLoadingScreen = true;
  97358. this._scene = scene;
  97359. }
  97360. /**
  97361. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  97362. * @param taskName defines the name of the new task
  97363. * @param meshesNames defines the name of meshes to load
  97364. * @param rootUrl defines the root url to use to locate files
  97365. * @param sceneFilename defines the filename of the scene file
  97366. * @returns a new {BABYLON.MeshAssetTask} object
  97367. */
  97368. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  97369. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  97370. this._tasks.push(task);
  97371. return task;
  97372. };
  97373. /**
  97374. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  97375. * @param taskName defines the name of the new task
  97376. * @param url defines the url of the file to load
  97377. * @returns a new {BABYLON.TextFileAssetTask} object
  97378. */
  97379. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  97380. var task = new TextFileAssetTask(taskName, url);
  97381. this._tasks.push(task);
  97382. return task;
  97383. };
  97384. /**
  97385. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  97386. * @param taskName defines the name of the new task
  97387. * @param url defines the url of the file to load
  97388. * @returns a new {BABYLON.BinaryFileAssetTask} object
  97389. */
  97390. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  97391. var task = new BinaryFileAssetTask(taskName, url);
  97392. this._tasks.push(task);
  97393. return task;
  97394. };
  97395. /**
  97396. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  97397. * @param taskName defines the name of the new task
  97398. * @param url defines the url of the file to load
  97399. * @returns a new {BABYLON.ImageAssetTask} object
  97400. */
  97401. AssetsManager.prototype.addImageTask = function (taskName, url) {
  97402. var task = new ImageAssetTask(taskName, url);
  97403. this._tasks.push(task);
  97404. return task;
  97405. };
  97406. /**
  97407. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  97408. * @param taskName defines the name of the new task
  97409. * @param url defines the url of the file to load
  97410. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97411. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  97412. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  97413. * @returns a new {BABYLON.TextureAssetTask} object
  97414. */
  97415. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  97416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97417. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  97418. this._tasks.push(task);
  97419. return task;
  97420. };
  97421. /**
  97422. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  97423. * @param taskName defines the name of the new task
  97424. * @param url defines the url of the file to load
  97425. * @param extensions defines the extension to use to load the cube map (can be null)
  97426. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97427. * @param files defines the list of files to load (can be null)
  97428. * @returns a new {BABYLON.CubeTextureAssetTask} object
  97429. */
  97430. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  97431. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  97432. this._tasks.push(task);
  97433. return task;
  97434. };
  97435. /**
  97436. *
  97437. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  97438. * @param taskName defines the name of the new task
  97439. * @param url defines the url of the file to load
  97440. * @param size defines the size you want for the cubemap (can be null)
  97441. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97442. * @param generateHarmonics defines if you want to automatically generate (true by default)
  97443. * @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)
  97444. * @param reserved Internal use only
  97445. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  97446. */
  97447. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  97448. if (noMipmap === void 0) { noMipmap = false; }
  97449. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97450. if (gammaSpace === void 0) { gammaSpace = false; }
  97451. if (reserved === void 0) { reserved = false; }
  97452. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  97453. this._tasks.push(task);
  97454. return task;
  97455. };
  97456. /**
  97457. * Remove a task from the assets manager.
  97458. * @param task the task to remove
  97459. */
  97460. AssetsManager.prototype.removeTask = function (task) {
  97461. var index = this._tasks.indexOf(task);
  97462. if (index > -1) {
  97463. this._tasks.splice(index, 1);
  97464. }
  97465. };
  97466. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  97467. this._waitingTasksCount--;
  97468. try {
  97469. if (this.onProgress) {
  97470. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  97471. }
  97472. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  97473. }
  97474. catch (e) {
  97475. BABYLON.Tools.Error("Error running progress callbacks.");
  97476. console.log(e);
  97477. }
  97478. if (this._waitingTasksCount === 0) {
  97479. try {
  97480. if (this.onFinish) {
  97481. this.onFinish(this._tasks);
  97482. }
  97483. // Let's remove successfull tasks
  97484. var currentTasks = this._tasks.slice();
  97485. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  97486. var task = currentTasks_1[_i];
  97487. if (task.taskState === AssetTaskState.DONE) {
  97488. var index = this._tasks.indexOf(task);
  97489. if (index > -1) {
  97490. this._tasks.splice(index, 1);
  97491. }
  97492. }
  97493. }
  97494. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97495. }
  97496. catch (e) {
  97497. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  97498. console.log(e);
  97499. }
  97500. this._isLoading = false;
  97501. this._scene.getEngine().hideLoadingUI();
  97502. }
  97503. };
  97504. AssetsManager.prototype._runTask = function (task) {
  97505. var _this = this;
  97506. var done = function () {
  97507. try {
  97508. if (_this.onTaskSuccess) {
  97509. _this.onTaskSuccess(task);
  97510. }
  97511. _this.onTaskSuccessObservable.notifyObservers(task);
  97512. _this._decreaseWaitingTasksCount(task);
  97513. }
  97514. catch (e) {
  97515. error("Error executing task success callbacks", e);
  97516. }
  97517. };
  97518. var error = function (message, exception) {
  97519. task._setErrorObject(message, exception);
  97520. if (_this.onTaskError) {
  97521. _this.onTaskError(task);
  97522. }
  97523. _this.onTaskErrorObservable.notifyObservers(task);
  97524. _this._decreaseWaitingTasksCount(task);
  97525. };
  97526. task.run(this._scene, done, error);
  97527. };
  97528. /**
  97529. * Reset the {BABYLON.AssetsManager} and remove all tasks
  97530. * @return the current instance of the {BABYLON.AssetsManager}
  97531. */
  97532. AssetsManager.prototype.reset = function () {
  97533. this._isLoading = false;
  97534. this._tasks = new Array();
  97535. return this;
  97536. };
  97537. /**
  97538. * Start the loading process
  97539. * @return the current instance of the {BABYLON.AssetsManager}
  97540. */
  97541. AssetsManager.prototype.load = function () {
  97542. if (this._isLoading) {
  97543. return this;
  97544. }
  97545. this._isLoading = true;
  97546. this._waitingTasksCount = this._tasks.length;
  97547. this._totalTasksCount = this._tasks.length;
  97548. if (this._waitingTasksCount === 0) {
  97549. this._isLoading = false;
  97550. if (this.onFinish) {
  97551. this.onFinish(this._tasks);
  97552. }
  97553. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97554. return this;
  97555. }
  97556. if (this.useDefaultLoadingScreen) {
  97557. this._scene.getEngine().displayLoadingUI();
  97558. }
  97559. for (var index = 0; index < this._tasks.length; index++) {
  97560. var task = this._tasks[index];
  97561. if (task.taskState === AssetTaskState.INIT) {
  97562. this._runTask(task);
  97563. }
  97564. }
  97565. return this;
  97566. };
  97567. return AssetsManager;
  97568. }());
  97569. BABYLON.AssetsManager = AssetsManager;
  97570. })(BABYLON || (BABYLON = {}));
  97571. //# sourceMappingURL=babylon.assetsManager.js.map
  97572. var BABYLON;
  97573. (function (BABYLON) {
  97574. var serializedGeometries = [];
  97575. var serializeGeometry = function (geometry, serializationGeometries) {
  97576. if (serializedGeometries[geometry.id]) {
  97577. return;
  97578. }
  97579. if (geometry.doNotSerialize) {
  97580. return;
  97581. }
  97582. if (geometry instanceof BABYLON.BoxGeometry) {
  97583. serializationGeometries.boxes.push(geometry.serialize());
  97584. }
  97585. else if (geometry instanceof BABYLON.SphereGeometry) {
  97586. serializationGeometries.spheres.push(geometry.serialize());
  97587. }
  97588. else if (geometry instanceof BABYLON.CylinderGeometry) {
  97589. serializationGeometries.cylinders.push(geometry.serialize());
  97590. }
  97591. else if (geometry instanceof BABYLON.TorusGeometry) {
  97592. serializationGeometries.toruses.push(geometry.serialize());
  97593. }
  97594. else if (geometry instanceof BABYLON.GroundGeometry) {
  97595. serializationGeometries.grounds.push(geometry.serialize());
  97596. }
  97597. else if (geometry instanceof BABYLON.Plane) {
  97598. serializationGeometries.planes.push(geometry.serialize());
  97599. }
  97600. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  97601. serializationGeometries.torusKnots.push(geometry.serialize());
  97602. }
  97603. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  97604. throw new Error("Unknown primitive type");
  97605. }
  97606. else {
  97607. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  97608. }
  97609. serializedGeometries[geometry.id] = true;
  97610. };
  97611. var serializeMesh = function (mesh, serializationScene) {
  97612. var serializationObject = {};
  97613. // Geometry
  97614. var geometry = mesh._geometry;
  97615. if (geometry) {
  97616. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  97617. // 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
  97618. serializeGeometry(geometry, serializationScene.geometries);
  97619. }
  97620. }
  97621. // Custom
  97622. if (mesh.serialize) {
  97623. mesh.serialize(serializationObject);
  97624. }
  97625. return serializationObject;
  97626. };
  97627. var finalizeSingleMesh = function (mesh, serializationObject) {
  97628. //only works if the mesh is already loaded
  97629. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97630. //serialize material
  97631. if (mesh.material) {
  97632. if (mesh.material instanceof BABYLON.MultiMaterial) {
  97633. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  97634. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97635. serializationObject.multiMaterials.push(mesh.material.serialize());
  97636. }
  97637. }
  97638. else {
  97639. serializationObject.materials = serializationObject.materials || [];
  97640. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97641. serializationObject.materials.push(mesh.material.serialize());
  97642. }
  97643. }
  97644. }
  97645. //serialize geometry
  97646. var geometry = mesh._geometry;
  97647. if (geometry) {
  97648. if (!serializationObject.geometries) {
  97649. serializationObject.geometries = {};
  97650. serializationObject.geometries.boxes = [];
  97651. serializationObject.geometries.spheres = [];
  97652. serializationObject.geometries.cylinders = [];
  97653. serializationObject.geometries.toruses = [];
  97654. serializationObject.geometries.grounds = [];
  97655. serializationObject.geometries.planes = [];
  97656. serializationObject.geometries.torusKnots = [];
  97657. serializationObject.geometries.vertexData = [];
  97658. }
  97659. serializeGeometry(geometry, serializationObject.geometries);
  97660. }
  97661. // Skeletons
  97662. if (mesh.skeleton) {
  97663. serializationObject.skeletons = serializationObject.skeletons || [];
  97664. serializationObject.skeletons.push(mesh.skeleton.serialize());
  97665. }
  97666. //serialize the actual mesh
  97667. serializationObject.meshes = serializationObject.meshes || [];
  97668. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97669. }
  97670. };
  97671. var SceneSerializer = /** @class */ (function () {
  97672. function SceneSerializer() {
  97673. }
  97674. SceneSerializer.ClearCache = function () {
  97675. serializedGeometries = [];
  97676. };
  97677. SceneSerializer.Serialize = function (scene) {
  97678. var serializationObject = {};
  97679. SceneSerializer.ClearCache();
  97680. // Scene
  97681. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  97682. serializationObject.autoClear = scene.autoClear;
  97683. serializationObject.clearColor = scene.clearColor.asArray();
  97684. serializationObject.ambientColor = scene.ambientColor.asArray();
  97685. serializationObject.gravity = scene.gravity.asArray();
  97686. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  97687. serializationObject.workerCollisions = scene.workerCollisions;
  97688. // Fog
  97689. if (scene.fogMode && scene.fogMode !== 0) {
  97690. serializationObject.fogMode = scene.fogMode;
  97691. serializationObject.fogColor = scene.fogColor.asArray();
  97692. serializationObject.fogStart = scene.fogStart;
  97693. serializationObject.fogEnd = scene.fogEnd;
  97694. serializationObject.fogDensity = scene.fogDensity;
  97695. }
  97696. //Physics
  97697. if (scene.isPhysicsEnabled()) {
  97698. var physicEngine = scene.getPhysicsEngine();
  97699. if (physicEngine) {
  97700. serializationObject.physicsEnabled = true;
  97701. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  97702. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  97703. }
  97704. }
  97705. // Metadata
  97706. if (scene.metadata) {
  97707. serializationObject.metadata = scene.metadata;
  97708. }
  97709. // Morph targets
  97710. serializationObject.morphTargetManagers = [];
  97711. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  97712. var abstractMesh = _a[_i];
  97713. var manager = abstractMesh.morphTargetManager;
  97714. if (manager) {
  97715. serializationObject.morphTargetManagers.push(manager.serialize());
  97716. }
  97717. }
  97718. // Lights
  97719. serializationObject.lights = [];
  97720. var index;
  97721. var light;
  97722. for (index = 0; index < scene.lights.length; index++) {
  97723. light = scene.lights[index];
  97724. if (!light.doNotSerialize) {
  97725. serializationObject.lights.push(light.serialize());
  97726. }
  97727. }
  97728. // Cameras
  97729. serializationObject.cameras = [];
  97730. for (index = 0; index < scene.cameras.length; index++) {
  97731. var camera = scene.cameras[index];
  97732. if (!camera.doNotSerialize) {
  97733. serializationObject.cameras.push(camera.serialize());
  97734. }
  97735. }
  97736. if (scene.activeCamera) {
  97737. serializationObject.activeCameraID = scene.activeCamera.id;
  97738. }
  97739. // Animations
  97740. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  97741. // Materials
  97742. serializationObject.materials = [];
  97743. serializationObject.multiMaterials = [];
  97744. var material;
  97745. for (index = 0; index < scene.materials.length; index++) {
  97746. material = scene.materials[index];
  97747. if (!material.doNotSerialize) {
  97748. serializationObject.materials.push(material.serialize());
  97749. }
  97750. }
  97751. // MultiMaterials
  97752. serializationObject.multiMaterials = [];
  97753. for (index = 0; index < scene.multiMaterials.length; index++) {
  97754. var multiMaterial = scene.multiMaterials[index];
  97755. serializationObject.multiMaterials.push(multiMaterial.serialize());
  97756. }
  97757. // Environment texture
  97758. if (scene.environmentTexture) {
  97759. serializationObject.environmentTexture = scene.environmentTexture.name;
  97760. }
  97761. // Skeletons
  97762. serializationObject.skeletons = [];
  97763. for (index = 0; index < scene.skeletons.length; index++) {
  97764. var skeleton = scene.skeletons[index];
  97765. if (!skeleton.doNotSerialize) {
  97766. serializationObject.skeletons.push(skeleton.serialize());
  97767. }
  97768. }
  97769. // Transform nodes
  97770. serializationObject.transformNodes = [];
  97771. for (index = 0; index < scene.transformNodes.length; index++) {
  97772. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  97773. }
  97774. // Geometries
  97775. serializationObject.geometries = {};
  97776. serializationObject.geometries.boxes = [];
  97777. serializationObject.geometries.spheres = [];
  97778. serializationObject.geometries.cylinders = [];
  97779. serializationObject.geometries.toruses = [];
  97780. serializationObject.geometries.grounds = [];
  97781. serializationObject.geometries.planes = [];
  97782. serializationObject.geometries.torusKnots = [];
  97783. serializationObject.geometries.vertexData = [];
  97784. serializedGeometries = [];
  97785. var geometries = scene.getGeometries();
  97786. for (index = 0; index < geometries.length; index++) {
  97787. var geometry = geometries[index];
  97788. if (geometry.isReady()) {
  97789. serializeGeometry(geometry, serializationObject.geometries);
  97790. }
  97791. }
  97792. // Meshes
  97793. serializationObject.meshes = [];
  97794. for (index = 0; index < scene.meshes.length; index++) {
  97795. var abstractMesh = scene.meshes[index];
  97796. if (abstractMesh instanceof BABYLON.Mesh) {
  97797. var mesh = abstractMesh;
  97798. if (!mesh.doNotSerialize) {
  97799. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97800. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97801. }
  97802. }
  97803. }
  97804. }
  97805. // Particles Systems
  97806. serializationObject.particleSystems = [];
  97807. for (index = 0; index < scene.particleSystems.length; index++) {
  97808. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  97809. }
  97810. // Lens flares
  97811. serializationObject.lensFlareSystems = [];
  97812. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  97813. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  97814. }
  97815. // Shadows
  97816. serializationObject.shadowGenerators = [];
  97817. for (index = 0; index < scene.lights.length; index++) {
  97818. light = scene.lights[index];
  97819. var shadowGenerator = light.getShadowGenerator();
  97820. if (shadowGenerator) {
  97821. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  97822. }
  97823. }
  97824. // Action Manager
  97825. if (scene.actionManager) {
  97826. serializationObject.actions = scene.actionManager.serialize("scene");
  97827. }
  97828. // Audio
  97829. serializationObject.sounds = [];
  97830. for (index = 0; index < scene.soundTracks.length; index++) {
  97831. var soundtrack = scene.soundTracks[index];
  97832. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  97833. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  97834. }
  97835. }
  97836. // Effect layers
  97837. serializationObject.effectLayers = [];
  97838. for (index = 0; index < scene.effectLayers.length; index++) {
  97839. var layer = scene.effectLayers[index];
  97840. if (layer.serialize) {
  97841. serializationObject.effectLayers.push(layer.serialize());
  97842. }
  97843. }
  97844. return serializationObject;
  97845. };
  97846. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  97847. if (withParents === void 0) { withParents = false; }
  97848. if (withChildren === void 0) { withChildren = false; }
  97849. var serializationObject = {};
  97850. SceneSerializer.ClearCache();
  97851. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  97852. if (withParents || withChildren) {
  97853. //deliberate for loop! not for each, appended should be processed as well.
  97854. for (var i = 0; i < toSerialize.length; ++i) {
  97855. if (withChildren) {
  97856. toSerialize[i].getDescendants().forEach(function (node) {
  97857. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  97858. toSerialize.push(node);
  97859. }
  97860. });
  97861. }
  97862. //make sure the array doesn't contain the object already
  97863. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  97864. toSerialize.push(toSerialize[i].parent);
  97865. }
  97866. }
  97867. }
  97868. toSerialize.forEach(function (mesh) {
  97869. finalizeSingleMesh(mesh, serializationObject);
  97870. });
  97871. return serializationObject;
  97872. };
  97873. return SceneSerializer;
  97874. }());
  97875. BABYLON.SceneSerializer = SceneSerializer;
  97876. })(BABYLON || (BABYLON = {}));
  97877. //# sourceMappingURL=babylon.sceneSerializer.js.map
  97878. var BABYLON;
  97879. (function (BABYLON) {
  97880. var ReflectionProbe = /** @class */ (function () {
  97881. function ReflectionProbe(name, size, scene, generateMipMaps) {
  97882. if (generateMipMaps === void 0) { generateMipMaps = true; }
  97883. var _this = this;
  97884. this.name = name;
  97885. this._viewMatrix = BABYLON.Matrix.Identity();
  97886. this._target = BABYLON.Vector3.Zero();
  97887. this._add = BABYLON.Vector3.Zero();
  97888. this._invertYAxis = false;
  97889. this.position = BABYLON.Vector3.Zero();
  97890. this._scene = scene;
  97891. this._scene.reflectionProbes.push(this);
  97892. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  97893. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  97894. switch (faceIndex) {
  97895. case 0:
  97896. _this._add.copyFromFloats(1, 0, 0);
  97897. break;
  97898. case 1:
  97899. _this._add.copyFromFloats(-1, 0, 0);
  97900. break;
  97901. case 2:
  97902. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  97903. break;
  97904. case 3:
  97905. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  97906. break;
  97907. case 4:
  97908. _this._add.copyFromFloats(0, 0, 1);
  97909. break;
  97910. case 5:
  97911. _this._add.copyFromFloats(0, 0, -1);
  97912. break;
  97913. }
  97914. if (_this._attachedMesh) {
  97915. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  97916. }
  97917. _this.position.addToRef(_this._add, _this._target);
  97918. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  97919. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  97920. scene._forcedViewPosition = _this.position;
  97921. });
  97922. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  97923. scene._forcedViewPosition = null;
  97924. scene.updateTransformMatrix(true);
  97925. });
  97926. if (scene.activeCamera) {
  97927. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  97928. }
  97929. }
  97930. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  97931. get: function () {
  97932. return this._renderTargetTexture.samples;
  97933. },
  97934. set: function (value) {
  97935. this._renderTargetTexture.samples = value;
  97936. },
  97937. enumerable: true,
  97938. configurable: true
  97939. });
  97940. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  97941. get: function () {
  97942. return this._renderTargetTexture.refreshRate;
  97943. },
  97944. set: function (value) {
  97945. this._renderTargetTexture.refreshRate = value;
  97946. },
  97947. enumerable: true,
  97948. configurable: true
  97949. });
  97950. ReflectionProbe.prototype.getScene = function () {
  97951. return this._scene;
  97952. };
  97953. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  97954. get: function () {
  97955. return this._renderTargetTexture;
  97956. },
  97957. enumerable: true,
  97958. configurable: true
  97959. });
  97960. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  97961. get: function () {
  97962. return this._renderTargetTexture.renderList;
  97963. },
  97964. enumerable: true,
  97965. configurable: true
  97966. });
  97967. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  97968. this._attachedMesh = mesh;
  97969. };
  97970. /**
  97971. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  97972. *
  97973. * @param renderingGroupId The rendering group id corresponding to its index
  97974. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  97975. */
  97976. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  97977. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  97978. };
  97979. ReflectionProbe.prototype.dispose = function () {
  97980. var index = this._scene.reflectionProbes.indexOf(this);
  97981. if (index !== -1) {
  97982. // Remove from the scene if found
  97983. this._scene.reflectionProbes.splice(index, 1);
  97984. }
  97985. if (this._renderTargetTexture) {
  97986. this._renderTargetTexture.dispose();
  97987. this._renderTargetTexture = null;
  97988. }
  97989. };
  97990. return ReflectionProbe;
  97991. }());
  97992. BABYLON.ReflectionProbe = ReflectionProbe;
  97993. })(BABYLON || (BABYLON = {}));
  97994. //# sourceMappingURL=babylon.reflectionProbe.js.map
  97995. var BABYLON;
  97996. (function (BABYLON) {
  97997. var Layer = /** @class */ (function () {
  97998. function Layer(name, imgUrl, scene, isBackground, color) {
  97999. this.name = name;
  98000. this.scale = new BABYLON.Vector2(1, 1);
  98001. this.offset = new BABYLON.Vector2(0, 0);
  98002. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  98003. this.layerMask = 0x0FFFFFFF;
  98004. this._vertexBuffers = {};
  98005. // Events
  98006. /**
  98007. * An event triggered when the layer is disposed.
  98008. */
  98009. this.onDisposeObservable = new BABYLON.Observable();
  98010. /**
  98011. * An event triggered before rendering the scene
  98012. */
  98013. this.onBeforeRenderObservable = new BABYLON.Observable();
  98014. /**
  98015. * An event triggered after rendering the scene
  98016. */
  98017. this.onAfterRenderObservable = new BABYLON.Observable();
  98018. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  98019. this.isBackground = isBackground === undefined ? true : isBackground;
  98020. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  98021. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  98022. this._scene.layers.push(this);
  98023. var engine = this._scene.getEngine();
  98024. // VBO
  98025. var vertices = [];
  98026. vertices.push(1, 1);
  98027. vertices.push(-1, 1);
  98028. vertices.push(-1, -1);
  98029. vertices.push(1, -1);
  98030. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  98031. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  98032. this._createIndexBuffer();
  98033. // Effects
  98034. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  98035. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  98036. }
  98037. Object.defineProperty(Layer.prototype, "onDispose", {
  98038. set: function (callback) {
  98039. if (this._onDisposeObserver) {
  98040. this.onDisposeObservable.remove(this._onDisposeObserver);
  98041. }
  98042. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  98043. },
  98044. enumerable: true,
  98045. configurable: true
  98046. });
  98047. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  98048. set: function (callback) {
  98049. if (this._onBeforeRenderObserver) {
  98050. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  98051. }
  98052. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  98053. },
  98054. enumerable: true,
  98055. configurable: true
  98056. });
  98057. Object.defineProperty(Layer.prototype, "onAfterRender", {
  98058. set: function (callback) {
  98059. if (this._onAfterRenderObserver) {
  98060. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98061. }
  98062. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  98063. },
  98064. enumerable: true,
  98065. configurable: true
  98066. });
  98067. Layer.prototype._createIndexBuffer = function () {
  98068. var engine = this._scene.getEngine();
  98069. // Indices
  98070. var indices = [];
  98071. indices.push(0);
  98072. indices.push(1);
  98073. indices.push(2);
  98074. indices.push(0);
  98075. indices.push(2);
  98076. indices.push(3);
  98077. this._indexBuffer = engine.createIndexBuffer(indices);
  98078. };
  98079. Layer.prototype._rebuild = function () {
  98080. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98081. if (vb) {
  98082. vb._rebuild();
  98083. }
  98084. this._createIndexBuffer();
  98085. };
  98086. Layer.prototype.render = function () {
  98087. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  98088. // Check
  98089. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  98090. return;
  98091. var engine = this._scene.getEngine();
  98092. this.onBeforeRenderObservable.notifyObservers(this);
  98093. // Render
  98094. engine.enableEffect(currentEffect);
  98095. engine.setState(false);
  98096. // Texture
  98097. currentEffect.setTexture("textureSampler", this.texture);
  98098. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  98099. // Color
  98100. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  98101. // Scale / offset
  98102. currentEffect.setVector2("offset", this.offset);
  98103. currentEffect.setVector2("scale", this.scale);
  98104. // VBOs
  98105. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  98106. // Draw order
  98107. if (!this.alphaTest) {
  98108. engine.setAlphaMode(this.alphaBlendingMode);
  98109. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98110. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  98111. }
  98112. else {
  98113. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98114. }
  98115. this.onAfterRenderObservable.notifyObservers(this);
  98116. };
  98117. Layer.prototype.dispose = function () {
  98118. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98119. if (vertexBuffer) {
  98120. vertexBuffer.dispose();
  98121. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  98122. }
  98123. if (this._indexBuffer) {
  98124. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  98125. this._indexBuffer = null;
  98126. }
  98127. if (this.texture) {
  98128. this.texture.dispose();
  98129. this.texture = null;
  98130. }
  98131. // Remove from scene
  98132. var index = this._scene.layers.indexOf(this);
  98133. this._scene.layers.splice(index, 1);
  98134. // Callback
  98135. this.onDisposeObservable.notifyObservers(this);
  98136. this.onDisposeObservable.clear();
  98137. this.onAfterRenderObservable.clear();
  98138. this.onBeforeRenderObservable.clear();
  98139. };
  98140. return Layer;
  98141. }());
  98142. BABYLON.Layer = Layer;
  98143. })(BABYLON || (BABYLON = {}));
  98144. //# sourceMappingURL=babylon.layer.js.map
  98145. var BABYLON;
  98146. (function (BABYLON) {
  98147. var TextureTools = /** @class */ (function () {
  98148. function TextureTools() {
  98149. }
  98150. /**
  98151. * Uses the GPU to create a copy texture rescaled at a given size
  98152. * @param texture Texture to copy from
  98153. * @param width Desired width
  98154. * @param height Desired height
  98155. * @return Generated texture
  98156. */
  98157. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  98158. if (useBilinearMode === void 0) { useBilinearMode = true; }
  98159. var scene = texture.getScene();
  98160. var engine = scene.getEngine();
  98161. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  98162. rtt.wrapU = texture.wrapU;
  98163. rtt.wrapV = texture.wrapV;
  98164. rtt.uOffset = texture.uOffset;
  98165. rtt.vOffset = texture.vOffset;
  98166. rtt.uScale = texture.uScale;
  98167. rtt.vScale = texture.vScale;
  98168. rtt.uAng = texture.uAng;
  98169. rtt.vAng = texture.vAng;
  98170. rtt.wAng = texture.wAng;
  98171. rtt.coordinatesIndex = texture.coordinatesIndex;
  98172. rtt.level = texture.level;
  98173. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  98174. rtt._texture.isReady = false;
  98175. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98176. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98177. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  98178. passPostProcess.getEffect().executeWhenCompiled(function () {
  98179. passPostProcess.onApply = function (effect) {
  98180. effect.setTexture("textureSampler", texture);
  98181. };
  98182. var internalTexture = rtt.getInternalTexture();
  98183. if (internalTexture) {
  98184. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  98185. engine.unBindFramebuffer(internalTexture);
  98186. rtt.disposeFramebufferObjects();
  98187. passPostProcess.dispose();
  98188. internalTexture.isReady = true;
  98189. }
  98190. });
  98191. return rtt;
  98192. };
  98193. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  98194. if (!scene._environmentBRDFTexture) {
  98195. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98196. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98197. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98198. scene._environmentBRDFTexture = texture;
  98199. }
  98200. return scene._environmentBRDFTexture;
  98201. };
  98202. 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=";
  98203. return TextureTools;
  98204. }());
  98205. BABYLON.TextureTools = TextureTools;
  98206. })(BABYLON || (BABYLON = {}));
  98207. //# sourceMappingURL=babylon.textureTools.js.map
  98208. var BABYLON;
  98209. (function (BABYLON) {
  98210. var FramingBehavior = /** @class */ (function () {
  98211. function FramingBehavior() {
  98212. this._mode = FramingBehavior.FitFrustumSidesMode;
  98213. this._radiusScale = 1.0;
  98214. this._positionScale = 0.5;
  98215. this._defaultElevation = 0.3;
  98216. this._elevationReturnTime = 1500;
  98217. this._elevationReturnWaitTime = 1000;
  98218. this._zoomStopsAnimation = false;
  98219. this._framingTime = 1500;
  98220. this._isPointerDown = false;
  98221. this._lastInteractionTime = -Infinity;
  98222. // Framing control
  98223. this._animatables = new Array();
  98224. this._betaIsAnimating = false;
  98225. }
  98226. Object.defineProperty(FramingBehavior.prototype, "name", {
  98227. get: function () {
  98228. return "Framing";
  98229. },
  98230. enumerable: true,
  98231. configurable: true
  98232. });
  98233. Object.defineProperty(FramingBehavior.prototype, "mode", {
  98234. /**
  98235. * Gets current mode used by the behavior.
  98236. */
  98237. get: function () {
  98238. return this._mode;
  98239. },
  98240. /**
  98241. * Sets the current mode used by the behavior
  98242. */
  98243. set: function (mode) {
  98244. this._mode = mode;
  98245. },
  98246. enumerable: true,
  98247. configurable: true
  98248. });
  98249. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  98250. /**
  98251. * Gets the scale applied to the radius
  98252. */
  98253. get: function () {
  98254. return this._radiusScale;
  98255. },
  98256. /**
  98257. * Sets the scale applied to the radius (1 by default)
  98258. */
  98259. set: function (radius) {
  98260. this._radiusScale = radius;
  98261. },
  98262. enumerable: true,
  98263. configurable: true
  98264. });
  98265. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  98266. /**
  98267. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98268. */
  98269. get: function () {
  98270. return this._positionScale;
  98271. },
  98272. /**
  98273. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98274. */
  98275. set: function (scale) {
  98276. this._positionScale = scale;
  98277. },
  98278. enumerable: true,
  98279. configurable: true
  98280. });
  98281. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  98282. /**
  98283. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98284. * behaviour is triggered, in radians.
  98285. */
  98286. get: function () {
  98287. return this._defaultElevation;
  98288. },
  98289. /**
  98290. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98291. * behaviour is triggered, in radians.
  98292. */
  98293. set: function (elevation) {
  98294. this._defaultElevation = elevation;
  98295. },
  98296. enumerable: true,
  98297. configurable: true
  98298. });
  98299. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  98300. /**
  98301. * Gets the time (in milliseconds) taken to return to the default beta position.
  98302. * Negative value indicates camera should not return to default.
  98303. */
  98304. get: function () {
  98305. return this._elevationReturnTime;
  98306. },
  98307. /**
  98308. * Sets the time (in milliseconds) taken to return to the default beta position.
  98309. * Negative value indicates camera should not return to default.
  98310. */
  98311. set: function (speed) {
  98312. this._elevationReturnTime = speed;
  98313. },
  98314. enumerable: true,
  98315. configurable: true
  98316. });
  98317. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  98318. /**
  98319. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98320. */
  98321. get: function () {
  98322. return this._elevationReturnWaitTime;
  98323. },
  98324. /**
  98325. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98326. */
  98327. set: function (time) {
  98328. this._elevationReturnWaitTime = time;
  98329. },
  98330. enumerable: true,
  98331. configurable: true
  98332. });
  98333. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  98334. /**
  98335. * Gets the flag that indicates if user zooming should stop animation.
  98336. */
  98337. get: function () {
  98338. return this._zoomStopsAnimation;
  98339. },
  98340. /**
  98341. * Sets the flag that indicates if user zooming should stop animation.
  98342. */
  98343. set: function (flag) {
  98344. this._zoomStopsAnimation = flag;
  98345. },
  98346. enumerable: true,
  98347. configurable: true
  98348. });
  98349. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  98350. /**
  98351. * Gets the transition time when framing the mesh, in milliseconds
  98352. */
  98353. get: function () {
  98354. return this._framingTime;
  98355. },
  98356. /**
  98357. * Sets the transition time when framing the mesh, in milliseconds
  98358. */
  98359. set: function (time) {
  98360. this._framingTime = time;
  98361. },
  98362. enumerable: true,
  98363. configurable: true
  98364. });
  98365. FramingBehavior.prototype.init = function () {
  98366. // Do notihng
  98367. };
  98368. FramingBehavior.prototype.attach = function (camera) {
  98369. var _this = this;
  98370. this._attachedCamera = camera;
  98371. var scene = this._attachedCamera.getScene();
  98372. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  98373. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98374. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98375. _this._isPointerDown = true;
  98376. return;
  98377. }
  98378. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98379. _this._isPointerDown = false;
  98380. }
  98381. });
  98382. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98383. if (mesh) {
  98384. _this.zoomOnMesh(mesh);
  98385. }
  98386. });
  98387. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98388. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98389. _this._applyUserInteraction();
  98390. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  98391. // back to the default position after a given timeout
  98392. _this._maintainCameraAboveGround();
  98393. });
  98394. };
  98395. FramingBehavior.prototype.detach = function () {
  98396. if (!this._attachedCamera) {
  98397. return;
  98398. }
  98399. var scene = this._attachedCamera.getScene();
  98400. if (this._onPrePointerObservableObserver) {
  98401. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98402. }
  98403. if (this._onAfterCheckInputsObserver) {
  98404. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98405. }
  98406. if (this._onMeshTargetChangedObserver) {
  98407. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98408. }
  98409. this._attachedCamera = null;
  98410. };
  98411. /**
  98412. * Targets the given mesh and updates zoom level accordingly.
  98413. * @param mesh The mesh to target.
  98414. * @param radius Optional. If a cached radius position already exists, overrides default.
  98415. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98416. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98417. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98418. */
  98419. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98420. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98421. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98422. mesh.computeWorldMatrix(true);
  98423. var boundingBox = mesh.getBoundingInfo().boundingBox;
  98424. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  98425. };
  98426. /**
  98427. * Targets the given mesh with its children and updates zoom level accordingly.
  98428. * @param mesh The mesh to target.
  98429. * @param radius Optional. If a cached radius position already exists, overrides default.
  98430. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98431. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98432. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98433. */
  98434. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98435. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98436. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98437. mesh.computeWorldMatrix(true);
  98438. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  98439. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  98440. };
  98441. /**
  98442. * Targets the given meshes with their children and updates zoom level accordingly.
  98443. * @param meshes The mesh to target.
  98444. * @param radius Optional. If a cached radius position already exists, overrides default.
  98445. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98446. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98447. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98448. */
  98449. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  98450. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98451. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98452. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  98453. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  98454. for (var i = 0; i < meshes.length; i++) {
  98455. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  98456. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  98457. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  98458. }
  98459. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  98460. };
  98461. /**
  98462. * Targets the given mesh and updates zoom level accordingly.
  98463. * @param mesh The mesh to target.
  98464. * @param radius Optional. If a cached radius position already exists, overrides default.
  98465. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98466. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98467. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98468. */
  98469. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  98470. var _this = this;
  98471. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98472. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98473. var zoomTarget;
  98474. if (!this._attachedCamera) {
  98475. return;
  98476. }
  98477. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  98478. var bottom = minimumWorld.y;
  98479. var top = maximumWorld.y;
  98480. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  98481. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  98482. if (focusOnOriginXZ) {
  98483. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  98484. }
  98485. else {
  98486. var centerWorld = minimumWorld.add(radiusWorld);
  98487. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  98488. }
  98489. if (!this._vectorTransition) {
  98490. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  98491. }
  98492. this._betaIsAnimating = true;
  98493. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  98494. if (animatable) {
  98495. this._animatables.push(animatable);
  98496. }
  98497. // sets the radius and lower radius bounds
  98498. // Small delta ensures camera is not always at lower zoom limit.
  98499. var radius = 0;
  98500. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  98501. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98502. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  98503. radius = position;
  98504. }
  98505. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98506. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98507. if (this._attachedCamera.lowerRadiusLimit === null) {
  98508. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  98509. }
  98510. }
  98511. // Set sensibilities
  98512. var extend = maximumWorld.subtract(minimumWorld).length();
  98513. this._attachedCamera.panningSensibility = 5000 / extend;
  98514. this._attachedCamera.wheelPrecision = 100 / radius;
  98515. // transition to new radius
  98516. if (!this._radiusTransition) {
  98517. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98518. }
  98519. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  98520. _this.stopAllAnimations();
  98521. if (onAnimationEnd) {
  98522. onAnimationEnd();
  98523. }
  98524. if (_this._attachedCamera) {
  98525. _this._attachedCamera.storeState();
  98526. }
  98527. });
  98528. if (animatable) {
  98529. this._animatables.push(animatable);
  98530. }
  98531. };
  98532. /**
  98533. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  98534. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  98535. * frustum width.
  98536. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  98537. * to fully enclose the mesh in the viewing frustum.
  98538. */
  98539. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  98540. var size = maximumWorld.subtract(minimumWorld);
  98541. var boxVectorGlobalDiagonal = size.length();
  98542. var frustumSlope = this._getFrustumSlope();
  98543. // Formula for setting distance
  98544. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  98545. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  98546. // Horizon distance
  98547. var radius = radiusWithoutFraming * this._radiusScale;
  98548. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  98549. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  98550. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  98551. var camera = this._attachedCamera;
  98552. if (!camera) {
  98553. return 0;
  98554. }
  98555. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98556. // Don't exceed the requested limit
  98557. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  98558. }
  98559. // Don't exceed the upper radius limit
  98560. if (camera.upperRadiusLimit) {
  98561. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  98562. }
  98563. return distance;
  98564. };
  98565. /**
  98566. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  98567. * is automatically returned to its default position (expected to be above ground plane).
  98568. */
  98569. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  98570. var _this = this;
  98571. if (this._elevationReturnTime < 0) {
  98572. return;
  98573. }
  98574. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  98575. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  98576. var limitBeta = Math.PI * 0.5;
  98577. // Bring the camera back up if below the ground plane
  98578. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  98579. this._betaIsAnimating = true;
  98580. //Transition to new position
  98581. this.stopAllAnimations();
  98582. if (!this._betaTransition) {
  98583. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98584. }
  98585. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  98586. _this._clearAnimationLocks();
  98587. _this.stopAllAnimations();
  98588. });
  98589. if (animatabe) {
  98590. this._animatables.push(animatabe);
  98591. }
  98592. }
  98593. };
  98594. /**
  98595. * Returns the frustum slope based on the canvas ratio and camera FOV
  98596. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  98597. */
  98598. FramingBehavior.prototype._getFrustumSlope = function () {
  98599. // Calculate the viewport ratio
  98600. // Aspect Ratio is Height/Width.
  98601. var camera = this._attachedCamera;
  98602. if (!camera) {
  98603. return BABYLON.Vector2.Zero();
  98604. }
  98605. var engine = camera.getScene().getEngine();
  98606. var aspectRatio = engine.getAspectRatio(camera);
  98607. // Camera FOV is the vertical field of view (top-bottom) in radians.
  98608. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  98609. var frustumSlopeY = Math.tan(camera.fov / 2);
  98610. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  98611. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  98612. // along the forward vector.
  98613. var frustumSlopeX = frustumSlopeY * aspectRatio;
  98614. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  98615. };
  98616. /**
  98617. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  98618. */
  98619. FramingBehavior.prototype._clearAnimationLocks = function () {
  98620. this._betaIsAnimating = false;
  98621. };
  98622. /**
  98623. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98624. */
  98625. FramingBehavior.prototype._applyUserInteraction = function () {
  98626. if (this.isUserIsMoving) {
  98627. this._lastInteractionTime = BABYLON.Tools.Now;
  98628. this.stopAllAnimations();
  98629. this._clearAnimationLocks();
  98630. }
  98631. };
  98632. /**
  98633. * Stops and removes all animations that have been applied to the camera
  98634. */
  98635. FramingBehavior.prototype.stopAllAnimations = function () {
  98636. if (this._attachedCamera) {
  98637. this._attachedCamera.animations = [];
  98638. }
  98639. while (this._animatables.length) {
  98640. if (this._animatables[0]) {
  98641. this._animatables[0].onAnimationEnd = null;
  98642. this._animatables[0].stop();
  98643. }
  98644. this._animatables.shift();
  98645. }
  98646. };
  98647. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  98648. /**
  98649. * Gets a value indicating if the user is moving the camera
  98650. */
  98651. get: function () {
  98652. if (!this._attachedCamera) {
  98653. return false;
  98654. }
  98655. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98656. this._attachedCamera.inertialBetaOffset !== 0 ||
  98657. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98658. this._attachedCamera.inertialPanningX !== 0 ||
  98659. this._attachedCamera.inertialPanningY !== 0 ||
  98660. this._isPointerDown;
  98661. },
  98662. enumerable: true,
  98663. configurable: true
  98664. });
  98665. /**
  98666. * The easing function used by animations
  98667. */
  98668. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  98669. /**
  98670. * The easing mode used by animations
  98671. */
  98672. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  98673. // Statics
  98674. /**
  98675. * The camera can move all the way towards the mesh.
  98676. */
  98677. FramingBehavior.IgnoreBoundsSizeMode = 0;
  98678. /**
  98679. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  98680. */
  98681. FramingBehavior.FitFrustumSidesMode = 1;
  98682. return FramingBehavior;
  98683. }());
  98684. BABYLON.FramingBehavior = FramingBehavior;
  98685. })(BABYLON || (BABYLON = {}));
  98686. //# sourceMappingURL=babylon.framingBehavior.js.map
  98687. var BABYLON;
  98688. (function (BABYLON) {
  98689. /**
  98690. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  98691. */
  98692. var BouncingBehavior = /** @class */ (function () {
  98693. function BouncingBehavior() {
  98694. /**
  98695. * The duration of the animation, in milliseconds
  98696. */
  98697. this.transitionDuration = 450;
  98698. /**
  98699. * Length of the distance animated by the transition when lower radius is reached
  98700. */
  98701. this.lowerRadiusTransitionRange = 2;
  98702. /**
  98703. * Length of the distance animated by the transition when upper radius is reached
  98704. */
  98705. this.upperRadiusTransitionRange = -2;
  98706. this._autoTransitionRange = false;
  98707. // Animations
  98708. this._radiusIsAnimating = false;
  98709. this._radiusBounceTransition = null;
  98710. this._animatables = new Array();
  98711. }
  98712. Object.defineProperty(BouncingBehavior.prototype, "name", {
  98713. get: function () {
  98714. return "Bouncing";
  98715. },
  98716. enumerable: true,
  98717. configurable: true
  98718. });
  98719. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  98720. /**
  98721. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98722. */
  98723. get: function () {
  98724. return this._autoTransitionRange;
  98725. },
  98726. /**
  98727. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98728. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  98729. */
  98730. set: function (value) {
  98731. var _this = this;
  98732. if (this._autoTransitionRange === value) {
  98733. return;
  98734. }
  98735. this._autoTransitionRange = value;
  98736. var camera = this._attachedCamera;
  98737. if (!camera) {
  98738. return;
  98739. }
  98740. if (value) {
  98741. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98742. if (!mesh) {
  98743. return;
  98744. }
  98745. mesh.computeWorldMatrix(true);
  98746. var diagonal = mesh.getBoundingInfo().diagonalLength;
  98747. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  98748. _this.upperRadiusTransitionRange = diagonal * 0.05;
  98749. });
  98750. }
  98751. else if (this._onMeshTargetChangedObserver) {
  98752. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98753. }
  98754. },
  98755. enumerable: true,
  98756. configurable: true
  98757. });
  98758. BouncingBehavior.prototype.init = function () {
  98759. // Do notihng
  98760. };
  98761. BouncingBehavior.prototype.attach = function (camera) {
  98762. var _this = this;
  98763. this._attachedCamera = camera;
  98764. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98765. if (!_this._attachedCamera) {
  98766. return;
  98767. }
  98768. // Add the bounce animation to the lower radius limit
  98769. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  98770. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  98771. }
  98772. // Add the bounce animation to the upper radius limit
  98773. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  98774. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  98775. }
  98776. });
  98777. };
  98778. BouncingBehavior.prototype.detach = function () {
  98779. if (!this._attachedCamera) {
  98780. return;
  98781. }
  98782. if (this._onAfterCheckInputsObserver) {
  98783. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98784. }
  98785. if (this._onMeshTargetChangedObserver) {
  98786. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98787. }
  98788. this._attachedCamera = null;
  98789. };
  98790. /**
  98791. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  98792. * @param radiusLimit The limit to check against.
  98793. * @return Bool to indicate if at limit.
  98794. */
  98795. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  98796. if (!this._attachedCamera) {
  98797. return false;
  98798. }
  98799. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  98800. return true;
  98801. }
  98802. return false;
  98803. };
  98804. /**
  98805. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  98806. * @param radiusDelta The delta by which to animate to. Can be negative.
  98807. */
  98808. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  98809. var _this = this;
  98810. if (!this._attachedCamera) {
  98811. return;
  98812. }
  98813. if (!this._radiusBounceTransition) {
  98814. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  98815. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  98816. }
  98817. // Prevent zoom until bounce has completed
  98818. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  98819. this._attachedCamera.wheelPrecision = Infinity;
  98820. this._attachedCamera.inertialRadiusOffset = 0;
  98821. // Animate to the radius limit
  98822. this.stopAllAnimations();
  98823. this._radiusIsAnimating = true;
  98824. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  98825. if (animatable) {
  98826. this._animatables.push(animatable);
  98827. }
  98828. };
  98829. /**
  98830. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  98831. */
  98832. BouncingBehavior.prototype._clearAnimationLocks = function () {
  98833. this._radiusIsAnimating = false;
  98834. if (this._attachedCamera) {
  98835. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  98836. }
  98837. };
  98838. /**
  98839. * Stops and removes all animations that have been applied to the camera
  98840. */
  98841. BouncingBehavior.prototype.stopAllAnimations = function () {
  98842. if (this._attachedCamera) {
  98843. this._attachedCamera.animations = [];
  98844. }
  98845. while (this._animatables.length) {
  98846. this._animatables[0].onAnimationEnd = null;
  98847. this._animatables[0].stop();
  98848. this._animatables.shift();
  98849. }
  98850. };
  98851. /**
  98852. * The easing function used by animations
  98853. */
  98854. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  98855. /**
  98856. * The easing mode used by animations
  98857. */
  98858. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  98859. return BouncingBehavior;
  98860. }());
  98861. BABYLON.BouncingBehavior = BouncingBehavior;
  98862. })(BABYLON || (BABYLON = {}));
  98863. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  98864. var BABYLON;
  98865. (function (BABYLON) {
  98866. var AutoRotationBehavior = /** @class */ (function () {
  98867. function AutoRotationBehavior() {
  98868. this._zoomStopsAnimation = false;
  98869. this._idleRotationSpeed = 0.05;
  98870. this._idleRotationWaitTime = 2000;
  98871. this._idleRotationSpinupTime = 2000;
  98872. this._isPointerDown = false;
  98873. this._lastFrameTime = null;
  98874. this._lastInteractionTime = -Infinity;
  98875. this._cameraRotationSpeed = 0;
  98876. this._lastFrameRadius = 0;
  98877. }
  98878. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  98879. get: function () {
  98880. return "AutoRotation";
  98881. },
  98882. enumerable: true,
  98883. configurable: true
  98884. });
  98885. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  98886. /**
  98887. * Gets the flag that indicates if user zooming should stop animation.
  98888. */
  98889. get: function () {
  98890. return this._zoomStopsAnimation;
  98891. },
  98892. /**
  98893. * Sets the flag that indicates if user zooming should stop animation.
  98894. */
  98895. set: function (flag) {
  98896. this._zoomStopsAnimation = flag;
  98897. },
  98898. enumerable: true,
  98899. configurable: true
  98900. });
  98901. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  98902. /**
  98903. * Gets the default speed at which the camera rotates around the model.
  98904. */
  98905. get: function () {
  98906. return this._idleRotationSpeed;
  98907. },
  98908. /**
  98909. * Sets the default speed at which the camera rotates around the model.
  98910. */
  98911. set: function (speed) {
  98912. this._idleRotationSpeed = speed;
  98913. },
  98914. enumerable: true,
  98915. configurable: true
  98916. });
  98917. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  98918. /**
  98919. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  98920. */
  98921. get: function () {
  98922. return this._idleRotationWaitTime;
  98923. },
  98924. /**
  98925. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  98926. */
  98927. set: function (time) {
  98928. this._idleRotationWaitTime = time;
  98929. },
  98930. enumerable: true,
  98931. configurable: true
  98932. });
  98933. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  98934. /**
  98935. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98936. */
  98937. get: function () {
  98938. return this._idleRotationSpinupTime;
  98939. },
  98940. /**
  98941. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98942. */
  98943. set: function (time) {
  98944. this._idleRotationSpinupTime = time;
  98945. },
  98946. enumerable: true,
  98947. configurable: true
  98948. });
  98949. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  98950. /**
  98951. * Gets a value indicating if the camera is currently rotating because of this behavior
  98952. */
  98953. get: function () {
  98954. return Math.abs(this._cameraRotationSpeed) > 0;
  98955. },
  98956. enumerable: true,
  98957. configurable: true
  98958. });
  98959. AutoRotationBehavior.prototype.init = function () {
  98960. // Do notihng
  98961. };
  98962. AutoRotationBehavior.prototype.attach = function (camera) {
  98963. var _this = this;
  98964. this._attachedCamera = camera;
  98965. var scene = this._attachedCamera.getScene();
  98966. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98967. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98968. _this._isPointerDown = true;
  98969. return;
  98970. }
  98971. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98972. _this._isPointerDown = false;
  98973. }
  98974. });
  98975. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98976. var now = BABYLON.Tools.Now;
  98977. var dt = 0;
  98978. if (_this._lastFrameTime != null) {
  98979. dt = now - _this._lastFrameTime;
  98980. }
  98981. _this._lastFrameTime = now;
  98982. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98983. _this._applyUserInteraction();
  98984. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  98985. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  98986. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  98987. // Step camera rotation by rotation speed
  98988. if (_this._attachedCamera) {
  98989. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  98990. }
  98991. });
  98992. };
  98993. AutoRotationBehavior.prototype.detach = function () {
  98994. if (!this._attachedCamera) {
  98995. return;
  98996. }
  98997. var scene = this._attachedCamera.getScene();
  98998. if (this._onPrePointerObservableObserver) {
  98999. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99000. }
  99001. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99002. this._attachedCamera = null;
  99003. };
  99004. /**
  99005. * Returns true if user is scrolling.
  99006. * @return true if user is scrolling.
  99007. */
  99008. AutoRotationBehavior.prototype._userIsZooming = function () {
  99009. if (!this._attachedCamera) {
  99010. return false;
  99011. }
  99012. return this._attachedCamera.inertialRadiusOffset !== 0;
  99013. };
  99014. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  99015. if (!this._attachedCamera) {
  99016. return false;
  99017. }
  99018. var zoomHasHitLimit = false;
  99019. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  99020. zoomHasHitLimit = true;
  99021. }
  99022. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  99023. this._lastFrameRadius = this._attachedCamera.radius;
  99024. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  99025. };
  99026. /**
  99027. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99028. */
  99029. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  99030. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  99031. this._lastInteractionTime = BABYLON.Tools.Now;
  99032. }
  99033. };
  99034. // Tools
  99035. AutoRotationBehavior.prototype._userIsMoving = function () {
  99036. if (!this._attachedCamera) {
  99037. return false;
  99038. }
  99039. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99040. this._attachedCamera.inertialBetaOffset !== 0 ||
  99041. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99042. this._attachedCamera.inertialPanningX !== 0 ||
  99043. this._attachedCamera.inertialPanningY !== 0 ||
  99044. this._isPointerDown;
  99045. };
  99046. return AutoRotationBehavior;
  99047. }());
  99048. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  99049. })(BABYLON || (BABYLON = {}));
  99050. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  99051. var BABYLON;
  99052. (function (BABYLON) {
  99053. var NullEngineOptions = /** @class */ (function () {
  99054. function NullEngineOptions() {
  99055. this.renderWidth = 512;
  99056. this.renderHeight = 256;
  99057. this.textureSize = 512;
  99058. this.deterministicLockstep = false;
  99059. this.lockstepMaxSteps = 4;
  99060. }
  99061. return NullEngineOptions;
  99062. }());
  99063. BABYLON.NullEngineOptions = NullEngineOptions;
  99064. /**
  99065. * The null engine class provides support for headless version of babylon.js.
  99066. * This can be used in server side scenario or for testing purposes
  99067. */
  99068. var NullEngine = /** @class */ (function (_super) {
  99069. __extends(NullEngine, _super);
  99070. function NullEngine(options) {
  99071. if (options === void 0) { options = new NullEngineOptions(); }
  99072. var _this = _super.call(this, null) || this;
  99073. if (options.deterministicLockstep === undefined) {
  99074. options.deterministicLockstep = false;
  99075. }
  99076. if (options.lockstepMaxSteps === undefined) {
  99077. options.lockstepMaxSteps = 4;
  99078. }
  99079. _this._options = options;
  99080. // Init caps
  99081. // We consider we are on a webgl1 capable device
  99082. _this._caps = new BABYLON.EngineCapabilities();
  99083. _this._caps.maxTexturesImageUnits = 16;
  99084. _this._caps.maxVertexTextureImageUnits = 16;
  99085. _this._caps.maxTextureSize = 512;
  99086. _this._caps.maxCubemapTextureSize = 512;
  99087. _this._caps.maxRenderTextureSize = 512;
  99088. _this._caps.maxVertexAttribs = 16;
  99089. _this._caps.maxVaryingVectors = 16;
  99090. _this._caps.maxFragmentUniformVectors = 16;
  99091. _this._caps.maxVertexUniformVectors = 16;
  99092. // Extensions
  99093. _this._caps.standardDerivatives = false;
  99094. _this._caps.astc = null;
  99095. _this._caps.s3tc = null;
  99096. _this._caps.pvrtc = null;
  99097. _this._caps.etc1 = null;
  99098. _this._caps.etc2 = null;
  99099. _this._caps.textureAnisotropicFilterExtension = null;
  99100. _this._caps.maxAnisotropy = 0;
  99101. _this._caps.uintIndices = false;
  99102. _this._caps.fragmentDepthSupported = false;
  99103. _this._caps.highPrecisionShaderSupported = true;
  99104. _this._caps.colorBufferFloat = false;
  99105. _this._caps.textureFloat = false;
  99106. _this._caps.textureFloatLinearFiltering = false;
  99107. _this._caps.textureFloatRender = false;
  99108. _this._caps.textureHalfFloat = false;
  99109. _this._caps.textureHalfFloatLinearFiltering = false;
  99110. _this._caps.textureHalfFloatRender = false;
  99111. _this._caps.textureLOD = false;
  99112. _this._caps.drawBuffersExtension = false;
  99113. _this._caps.depthTextureExtension = false;
  99114. _this._caps.vertexArrayObject = false;
  99115. _this._caps.instancedArrays = false;
  99116. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  99117. // Wrappers
  99118. if (typeof URL === "undefined") {
  99119. URL = {
  99120. createObjectURL: function () { },
  99121. revokeObjectURL: function () { }
  99122. };
  99123. }
  99124. if (typeof Blob === "undefined") {
  99125. Blob = function () { };
  99126. }
  99127. return _this;
  99128. }
  99129. NullEngine.prototype.isDeterministicLockStep = function () {
  99130. return this._options.deterministicLockstep;
  99131. };
  99132. NullEngine.prototype.getLockstepMaxSteps = function () {
  99133. return this._options.lockstepMaxSteps;
  99134. };
  99135. NullEngine.prototype.getHardwareScalingLevel = function () {
  99136. return 1.0;
  99137. };
  99138. NullEngine.prototype.createVertexBuffer = function (vertices) {
  99139. return {
  99140. capacity: 0,
  99141. references: 1,
  99142. is32Bits: false
  99143. };
  99144. };
  99145. NullEngine.prototype.createIndexBuffer = function (indices) {
  99146. return {
  99147. capacity: 0,
  99148. references: 1,
  99149. is32Bits: false
  99150. };
  99151. };
  99152. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  99153. if (stencil === void 0) { stencil = false; }
  99154. };
  99155. NullEngine.prototype.getRenderWidth = function (useScreen) {
  99156. if (useScreen === void 0) { useScreen = false; }
  99157. if (!useScreen && this._currentRenderTarget) {
  99158. return this._currentRenderTarget.width;
  99159. }
  99160. return this._options.renderWidth;
  99161. };
  99162. NullEngine.prototype.getRenderHeight = function (useScreen) {
  99163. if (useScreen === void 0) { useScreen = false; }
  99164. if (!useScreen && this._currentRenderTarget) {
  99165. return this._currentRenderTarget.height;
  99166. }
  99167. return this._options.renderHeight;
  99168. };
  99169. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  99170. this._cachedViewport = viewport;
  99171. };
  99172. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  99173. return {
  99174. transformFeedback: null,
  99175. __SPECTOR_rebuildProgram: null
  99176. };
  99177. };
  99178. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  99179. return [];
  99180. };
  99181. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  99182. return [];
  99183. };
  99184. NullEngine.prototype.bindSamplers = function (effect) {
  99185. this._currentEffect = null;
  99186. };
  99187. NullEngine.prototype.enableEffect = function (effect) {
  99188. this._currentEffect = effect;
  99189. if (effect.onBind) {
  99190. effect.onBind(effect);
  99191. }
  99192. effect.onBindObservable.notifyObservers(effect);
  99193. };
  99194. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  99195. if (zOffset === void 0) { zOffset = 0; }
  99196. if (reverseSide === void 0) { reverseSide = false; }
  99197. };
  99198. NullEngine.prototype.setIntArray = function (uniform, array) {
  99199. };
  99200. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  99201. };
  99202. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  99203. };
  99204. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  99205. };
  99206. NullEngine.prototype.setFloatArray = function (uniform, array) {
  99207. };
  99208. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  99209. };
  99210. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  99211. };
  99212. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  99213. };
  99214. NullEngine.prototype.setArray = function (uniform, array) {
  99215. };
  99216. NullEngine.prototype.setArray2 = function (uniform, array) {
  99217. };
  99218. NullEngine.prototype.setArray3 = function (uniform, array) {
  99219. };
  99220. NullEngine.prototype.setArray4 = function (uniform, array) {
  99221. };
  99222. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  99223. };
  99224. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  99225. };
  99226. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  99227. };
  99228. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  99229. };
  99230. NullEngine.prototype.setFloat = function (uniform, value) {
  99231. };
  99232. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  99233. };
  99234. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  99235. };
  99236. NullEngine.prototype.setBool = function (uniform, bool) {
  99237. };
  99238. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  99239. };
  99240. NullEngine.prototype.setColor3 = function (uniform, color3) {
  99241. };
  99242. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  99243. };
  99244. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  99245. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  99246. if (this._alphaMode === mode) {
  99247. return;
  99248. }
  99249. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  99250. if (!noDepthWriteChange) {
  99251. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  99252. }
  99253. this._alphaMode = mode;
  99254. };
  99255. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  99256. };
  99257. NullEngine.prototype.wipeCaches = function (bruteForce) {
  99258. if (this.preventCacheWipeBetweenFrames) {
  99259. return;
  99260. }
  99261. this.resetTextureCache();
  99262. this._currentEffect = null;
  99263. if (bruteForce) {
  99264. this._currentProgram = null;
  99265. this._stencilState.reset();
  99266. this._depthCullingState.reset();
  99267. this._alphaState.reset();
  99268. }
  99269. this._cachedVertexBuffers = null;
  99270. this._cachedIndexBuffer = null;
  99271. this._cachedEffectForVertexBuffers = null;
  99272. };
  99273. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  99274. };
  99275. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  99276. };
  99277. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  99278. };
  99279. NullEngine.prototype._createTexture = function () {
  99280. return {};
  99281. };
  99282. NullEngine.prototype._releaseTexture = function (texture) {
  99283. };
  99284. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  99285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99286. if (onLoad === void 0) { onLoad = null; }
  99287. if (onError === void 0) { onError = null; }
  99288. if (buffer === void 0) { buffer = null; }
  99289. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  99290. var url = String(urlArg);
  99291. texture.url = url;
  99292. texture.generateMipMaps = !noMipmap;
  99293. texture.samplingMode = samplingMode;
  99294. texture.invertY = invertY;
  99295. texture.baseWidth = this._options.textureSize;
  99296. texture.baseHeight = this._options.textureSize;
  99297. texture.width = this._options.textureSize;
  99298. texture.height = this._options.textureSize;
  99299. if (format) {
  99300. texture.format = format;
  99301. }
  99302. texture.isReady = true;
  99303. if (onLoad) {
  99304. onLoad();
  99305. }
  99306. this._internalTexturesCache.push(texture);
  99307. return texture;
  99308. };
  99309. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  99310. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  99311. if (options !== undefined && typeof options === "object") {
  99312. fullOptions.generateMipMaps = options.generateMipMaps;
  99313. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  99314. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  99315. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  99316. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  99317. }
  99318. else {
  99319. fullOptions.generateMipMaps = options;
  99320. fullOptions.generateDepthBuffer = true;
  99321. fullOptions.generateStencilBuffer = false;
  99322. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99323. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  99324. }
  99325. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  99326. var width = size.width || size;
  99327. var height = size.height || size;
  99328. texture._depthStencilBuffer = {};
  99329. texture._framebuffer = {};
  99330. texture.baseWidth = width;
  99331. texture.baseHeight = height;
  99332. texture.width = width;
  99333. texture.height = height;
  99334. texture.isReady = true;
  99335. texture.samples = 1;
  99336. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  99337. texture.samplingMode = fullOptions.samplingMode;
  99338. texture.type = fullOptions.type;
  99339. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  99340. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  99341. this._internalTexturesCache.push(texture);
  99342. return texture;
  99343. };
  99344. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  99345. texture.samplingMode = samplingMode;
  99346. };
  99347. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  99348. if (this._currentRenderTarget) {
  99349. this.unBindFramebuffer(this._currentRenderTarget);
  99350. }
  99351. this._currentRenderTarget = texture;
  99352. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  99353. if (this._cachedViewport && !forceFullscreenViewport) {
  99354. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  99355. }
  99356. };
  99357. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  99358. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  99359. this._currentRenderTarget = null;
  99360. if (onBeforeUnbind) {
  99361. if (texture._MSAAFramebuffer) {
  99362. this._currentFramebuffer = texture._framebuffer;
  99363. }
  99364. onBeforeUnbind();
  99365. }
  99366. this._currentFramebuffer = null;
  99367. };
  99368. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  99369. var vbo = {
  99370. capacity: 1,
  99371. references: 1,
  99372. is32Bits: false
  99373. };
  99374. return vbo;
  99375. };
  99376. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  99377. if (premulAlpha === void 0) { premulAlpha = false; }
  99378. };
  99379. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  99380. if (offset === void 0) { offset = 0; }
  99381. };
  99382. /**
  99383. * Updates a dynamic vertex buffer.
  99384. * @param vertexBuffer the vertex buffer to update
  99385. * @param data the data used to update the vertex buffer
  99386. * @param byteOffset the byte offset of the data (optional)
  99387. * @param byteLength the byte length of the data (optional)
  99388. */
  99389. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  99390. };
  99391. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  99392. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  99393. this._boundTexturesCache[this._activeChannel] = texture;
  99394. return true;
  99395. }
  99396. return false;
  99397. };
  99398. NullEngine.prototype._bindTexture = function (channel, texture) {
  99399. if (channel < 0) {
  99400. return;
  99401. }
  99402. this._bindTextureDirectly(0, texture);
  99403. };
  99404. NullEngine.prototype._releaseBuffer = function (buffer) {
  99405. buffer.references--;
  99406. if (buffer.references === 0) {
  99407. return true;
  99408. }
  99409. return false;
  99410. };
  99411. NullEngine.prototype.releaseEffects = function () {
  99412. };
  99413. return NullEngine;
  99414. }(BABYLON.Engine));
  99415. BABYLON.NullEngine = NullEngine;
  99416. })(BABYLON || (BABYLON = {}));
  99417. //# sourceMappingURL=babylon.nullEngine.js.map
  99418. var BABYLON;
  99419. (function (BABYLON) {
  99420. /**
  99421. * This class can be used to get instrumentation data from a Babylon engine
  99422. */
  99423. var EngineInstrumentation = /** @class */ (function () {
  99424. function EngineInstrumentation(engine) {
  99425. this.engine = engine;
  99426. this._captureGPUFrameTime = false;
  99427. this._gpuFrameTime = new BABYLON.PerfCounter();
  99428. this._captureShaderCompilationTime = false;
  99429. this._shaderCompilationTime = new BABYLON.PerfCounter();
  99430. // Observers
  99431. this._onBeginFrameObserver = null;
  99432. this._onEndFrameObserver = null;
  99433. this._onBeforeShaderCompilationObserver = null;
  99434. this._onAfterShaderCompilationObserver = null;
  99435. }
  99436. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  99437. // Properties
  99438. /**
  99439. * Gets the perf counter used for GPU frame time
  99440. */
  99441. get: function () {
  99442. return this._gpuFrameTime;
  99443. },
  99444. enumerable: true,
  99445. configurable: true
  99446. });
  99447. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  99448. /**
  99449. * Gets the GPU frame time capture status
  99450. */
  99451. get: function () {
  99452. return this._captureGPUFrameTime;
  99453. },
  99454. /**
  99455. * Enable or disable the GPU frame time capture
  99456. */
  99457. set: function (value) {
  99458. var _this = this;
  99459. if (value === this._captureGPUFrameTime) {
  99460. return;
  99461. }
  99462. this._captureGPUFrameTime = value;
  99463. if (value) {
  99464. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  99465. if (!_this._gpuFrameTimeToken) {
  99466. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  99467. }
  99468. });
  99469. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  99470. if (!_this._gpuFrameTimeToken) {
  99471. return;
  99472. }
  99473. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  99474. if (time > -1) {
  99475. _this._gpuFrameTimeToken = null;
  99476. _this._gpuFrameTime.fetchNewFrame();
  99477. _this._gpuFrameTime.addCount(time, true);
  99478. }
  99479. });
  99480. }
  99481. else {
  99482. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99483. this._onBeginFrameObserver = null;
  99484. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99485. this._onEndFrameObserver = null;
  99486. }
  99487. },
  99488. enumerable: true,
  99489. configurable: true
  99490. });
  99491. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  99492. /**
  99493. * Gets the perf counter used for shader compilation time
  99494. */
  99495. get: function () {
  99496. return this._shaderCompilationTime;
  99497. },
  99498. enumerable: true,
  99499. configurable: true
  99500. });
  99501. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  99502. /**
  99503. * Gets the shader compilation time capture status
  99504. */
  99505. get: function () {
  99506. return this._captureShaderCompilationTime;
  99507. },
  99508. /**
  99509. * Enable or disable the shader compilation time capture
  99510. */
  99511. set: function (value) {
  99512. var _this = this;
  99513. if (value === this._captureShaderCompilationTime) {
  99514. return;
  99515. }
  99516. this._captureShaderCompilationTime = value;
  99517. if (value) {
  99518. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  99519. _this._shaderCompilationTime.fetchNewFrame();
  99520. _this._shaderCompilationTime.beginMonitoring();
  99521. });
  99522. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  99523. _this._shaderCompilationTime.endMonitoring();
  99524. });
  99525. }
  99526. else {
  99527. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99528. this._onBeforeShaderCompilationObserver = null;
  99529. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99530. this._onAfterShaderCompilationObserver = null;
  99531. }
  99532. },
  99533. enumerable: true,
  99534. configurable: true
  99535. });
  99536. EngineInstrumentation.prototype.dispose = function () {
  99537. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99538. this._onBeginFrameObserver = null;
  99539. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99540. this._onEndFrameObserver = null;
  99541. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99542. this._onBeforeShaderCompilationObserver = null;
  99543. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99544. this._onAfterShaderCompilationObserver = null;
  99545. this.engine = null;
  99546. };
  99547. return EngineInstrumentation;
  99548. }());
  99549. BABYLON.EngineInstrumentation = EngineInstrumentation;
  99550. })(BABYLON || (BABYLON = {}));
  99551. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  99552. var BABYLON;
  99553. (function (BABYLON) {
  99554. /**
  99555. * This class can be used to get instrumentation data from a Babylon engine
  99556. */
  99557. var SceneInstrumentation = /** @class */ (function () {
  99558. function SceneInstrumentation(scene) {
  99559. var _this = this;
  99560. this.scene = scene;
  99561. this._captureActiveMeshesEvaluationTime = false;
  99562. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  99563. this._captureRenderTargetsRenderTime = false;
  99564. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  99565. this._captureFrameTime = false;
  99566. this._frameTime = new BABYLON.PerfCounter();
  99567. this._captureRenderTime = false;
  99568. this._renderTime = new BABYLON.PerfCounter();
  99569. this._captureInterFrameTime = false;
  99570. this._interFrameTime = new BABYLON.PerfCounter();
  99571. this._captureParticlesRenderTime = false;
  99572. this._particlesRenderTime = new BABYLON.PerfCounter();
  99573. this._captureSpritesRenderTime = false;
  99574. this._spritesRenderTime = new BABYLON.PerfCounter();
  99575. this._capturePhysicsTime = false;
  99576. this._physicsTime = new BABYLON.PerfCounter();
  99577. this._captureAnimationsTime = false;
  99578. this._animationsTime = new BABYLON.PerfCounter();
  99579. this._captureCameraRenderTime = false;
  99580. this._cameraRenderTime = new BABYLON.PerfCounter();
  99581. // Observers
  99582. this._onBeforeActiveMeshesEvaluationObserver = null;
  99583. this._onAfterActiveMeshesEvaluationObserver = null;
  99584. this._onBeforeRenderTargetsRenderObserver = null;
  99585. this._onAfterRenderTargetsRenderObserver = null;
  99586. this._onAfterRenderObserver = null;
  99587. this._onBeforeDrawPhaseObserver = null;
  99588. this._onAfterDrawPhaseObserver = null;
  99589. this._onBeforeAnimationsObserver = null;
  99590. this._onBeforeParticlesRenderingObserver = null;
  99591. this._onAfterParticlesRenderingObserver = null;
  99592. this._onBeforeSpritesRenderingObserver = null;
  99593. this._onAfterSpritesRenderingObserver = null;
  99594. this._onBeforePhysicsObserver = null;
  99595. this._onAfterPhysicsObserver = null;
  99596. this._onAfterAnimationsObserver = null;
  99597. this._onBeforeCameraRenderObserver = null;
  99598. this._onAfterCameraRenderObserver = null;
  99599. // Before render
  99600. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  99601. if (_this._captureActiveMeshesEvaluationTime) {
  99602. _this._activeMeshesEvaluationTime.fetchNewFrame();
  99603. }
  99604. if (_this._captureRenderTargetsRenderTime) {
  99605. _this._renderTargetsRenderTime.fetchNewFrame();
  99606. }
  99607. if (_this._captureFrameTime) {
  99608. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  99609. _this._frameTime.beginMonitoring();
  99610. }
  99611. if (_this._captureInterFrameTime) {
  99612. _this._interFrameTime.endMonitoring();
  99613. }
  99614. if (_this._captureParticlesRenderTime) {
  99615. _this._particlesRenderTime.fetchNewFrame();
  99616. }
  99617. if (_this._captureSpritesRenderTime) {
  99618. _this._spritesRenderTime.fetchNewFrame();
  99619. }
  99620. if (_this._captureAnimationsTime) {
  99621. _this._animationsTime.beginMonitoring();
  99622. }
  99623. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  99624. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  99625. });
  99626. // After render
  99627. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  99628. if (_this._captureFrameTime) {
  99629. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  99630. _this._frameTime.endMonitoring();
  99631. }
  99632. if (_this._captureRenderTime) {
  99633. _this._renderTime.endMonitoring(false);
  99634. }
  99635. if (_this._captureInterFrameTime) {
  99636. _this._interFrameTime.beginMonitoring();
  99637. }
  99638. });
  99639. }
  99640. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  99641. // Properties
  99642. /**
  99643. * Gets the perf counter used for active meshes evaluation time
  99644. */
  99645. get: function () {
  99646. return this._activeMeshesEvaluationTime;
  99647. },
  99648. enumerable: true,
  99649. configurable: true
  99650. });
  99651. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  99652. /**
  99653. * Gets the active meshes evaluation time capture status
  99654. */
  99655. get: function () {
  99656. return this._captureActiveMeshesEvaluationTime;
  99657. },
  99658. /**
  99659. * Enable or disable the active meshes evaluation time capture
  99660. */
  99661. set: function (value) {
  99662. var _this = this;
  99663. if (value === this._captureActiveMeshesEvaluationTime) {
  99664. return;
  99665. }
  99666. this._captureActiveMeshesEvaluationTime = value;
  99667. if (value) {
  99668. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  99669. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  99670. _this._activeMeshesEvaluationTime.beginMonitoring();
  99671. });
  99672. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  99673. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  99674. _this._activeMeshesEvaluationTime.endMonitoring();
  99675. });
  99676. }
  99677. else {
  99678. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99679. this._onBeforeActiveMeshesEvaluationObserver = null;
  99680. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99681. this._onAfterActiveMeshesEvaluationObserver = null;
  99682. }
  99683. },
  99684. enumerable: true,
  99685. configurable: true
  99686. });
  99687. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  99688. /**
  99689. * Gets the perf counter used for render targets render time
  99690. */
  99691. get: function () {
  99692. return this._renderTargetsRenderTime;
  99693. },
  99694. enumerable: true,
  99695. configurable: true
  99696. });
  99697. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  99698. /**
  99699. * Gets the render targets render time capture status
  99700. */
  99701. get: function () {
  99702. return this._captureRenderTargetsRenderTime;
  99703. },
  99704. /**
  99705. * Enable or disable the render targets render time capture
  99706. */
  99707. set: function (value) {
  99708. var _this = this;
  99709. if (value === this._captureRenderTargetsRenderTime) {
  99710. return;
  99711. }
  99712. this._captureRenderTargetsRenderTime = value;
  99713. if (value) {
  99714. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  99715. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  99716. _this._renderTargetsRenderTime.beginMonitoring();
  99717. });
  99718. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  99719. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  99720. _this._renderTargetsRenderTime.endMonitoring(false);
  99721. });
  99722. }
  99723. else {
  99724. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99725. this._onBeforeRenderTargetsRenderObserver = null;
  99726. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99727. this._onAfterRenderTargetsRenderObserver = null;
  99728. }
  99729. },
  99730. enumerable: true,
  99731. configurable: true
  99732. });
  99733. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  99734. /**
  99735. * Gets the perf counter used for particles render time
  99736. */
  99737. get: function () {
  99738. return this._particlesRenderTime;
  99739. },
  99740. enumerable: true,
  99741. configurable: true
  99742. });
  99743. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  99744. /**
  99745. * Gets the particles render time capture status
  99746. */
  99747. get: function () {
  99748. return this._captureParticlesRenderTime;
  99749. },
  99750. /**
  99751. * Enable or disable the particles render time capture
  99752. */
  99753. set: function (value) {
  99754. var _this = this;
  99755. if (value === this._captureParticlesRenderTime) {
  99756. return;
  99757. }
  99758. this._captureParticlesRenderTime = value;
  99759. if (value) {
  99760. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  99761. BABYLON.Tools.StartPerformanceCounter("Particles");
  99762. _this._particlesRenderTime.beginMonitoring();
  99763. });
  99764. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  99765. BABYLON.Tools.EndPerformanceCounter("Particles");
  99766. _this._particlesRenderTime.endMonitoring(false);
  99767. });
  99768. }
  99769. else {
  99770. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99771. this._onBeforeParticlesRenderingObserver = null;
  99772. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99773. this._onAfterParticlesRenderingObserver = null;
  99774. }
  99775. },
  99776. enumerable: true,
  99777. configurable: true
  99778. });
  99779. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  99780. /**
  99781. * Gets the perf counter used for sprites render time
  99782. */
  99783. get: function () {
  99784. return this._spritesRenderTime;
  99785. },
  99786. enumerable: true,
  99787. configurable: true
  99788. });
  99789. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  99790. /**
  99791. * Gets the sprites render time capture status
  99792. */
  99793. get: function () {
  99794. return this._captureSpritesRenderTime;
  99795. },
  99796. /**
  99797. * Enable or disable the sprites render time capture
  99798. */
  99799. set: function (value) {
  99800. var _this = this;
  99801. if (value === this._captureSpritesRenderTime) {
  99802. return;
  99803. }
  99804. this._captureSpritesRenderTime = value;
  99805. if (value) {
  99806. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  99807. BABYLON.Tools.StartPerformanceCounter("Sprites");
  99808. _this._spritesRenderTime.beginMonitoring();
  99809. });
  99810. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  99811. BABYLON.Tools.EndPerformanceCounter("Sprites");
  99812. _this._spritesRenderTime.endMonitoring(false);
  99813. });
  99814. }
  99815. else {
  99816. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99817. this._onBeforeSpritesRenderingObserver = null;
  99818. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99819. this._onAfterSpritesRenderingObserver = null;
  99820. }
  99821. },
  99822. enumerable: true,
  99823. configurable: true
  99824. });
  99825. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  99826. /**
  99827. * Gets the perf counter used for physics time
  99828. */
  99829. get: function () {
  99830. return this._physicsTime;
  99831. },
  99832. enumerable: true,
  99833. configurable: true
  99834. });
  99835. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  99836. /**
  99837. * Gets the physics time capture status
  99838. */
  99839. get: function () {
  99840. return this._capturePhysicsTime;
  99841. },
  99842. /**
  99843. * Enable or disable the physics time capture
  99844. */
  99845. set: function (value) {
  99846. var _this = this;
  99847. if (value === this._capturePhysicsTime) {
  99848. return;
  99849. }
  99850. this._capturePhysicsTime = value;
  99851. if (value) {
  99852. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  99853. BABYLON.Tools.StartPerformanceCounter("Physics");
  99854. _this._physicsTime.beginMonitoring();
  99855. });
  99856. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  99857. BABYLON.Tools.EndPerformanceCounter("Physics");
  99858. _this._physicsTime.endMonitoring();
  99859. });
  99860. }
  99861. else {
  99862. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99863. this._onBeforePhysicsObserver = null;
  99864. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99865. this._onAfterPhysicsObserver = null;
  99866. }
  99867. },
  99868. enumerable: true,
  99869. configurable: true
  99870. });
  99871. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  99872. /**
  99873. * Gets the perf counter used for animations time
  99874. */
  99875. get: function () {
  99876. return this._animationsTime;
  99877. },
  99878. enumerable: true,
  99879. configurable: true
  99880. });
  99881. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  99882. /**
  99883. * Gets the animations time capture status
  99884. */
  99885. get: function () {
  99886. return this._captureAnimationsTime;
  99887. },
  99888. /**
  99889. * Enable or disable the animations time capture
  99890. */
  99891. set: function (value) {
  99892. var _this = this;
  99893. if (value === this._captureAnimationsTime) {
  99894. return;
  99895. }
  99896. this._captureAnimationsTime = value;
  99897. if (value) {
  99898. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  99899. _this._animationsTime.endMonitoring();
  99900. });
  99901. }
  99902. else {
  99903. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99904. this._onAfterAnimationsObserver = null;
  99905. }
  99906. },
  99907. enumerable: true,
  99908. configurable: true
  99909. });
  99910. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  99911. /**
  99912. * Gets the perf counter used for frame time capture
  99913. */
  99914. get: function () {
  99915. return this._frameTime;
  99916. },
  99917. enumerable: true,
  99918. configurable: true
  99919. });
  99920. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  99921. /**
  99922. * Gets the frame time capture status
  99923. */
  99924. get: function () {
  99925. return this._captureFrameTime;
  99926. },
  99927. /**
  99928. * Enable or disable the frame time capture
  99929. */
  99930. set: function (value) {
  99931. this._captureFrameTime = value;
  99932. },
  99933. enumerable: true,
  99934. configurable: true
  99935. });
  99936. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  99937. /**
  99938. * Gets the perf counter used for inter-frames time capture
  99939. */
  99940. get: function () {
  99941. return this._interFrameTime;
  99942. },
  99943. enumerable: true,
  99944. configurable: true
  99945. });
  99946. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  99947. /**
  99948. * Gets the inter-frames time capture status
  99949. */
  99950. get: function () {
  99951. return this._captureInterFrameTime;
  99952. },
  99953. /**
  99954. * Enable or disable the inter-frames time capture
  99955. */
  99956. set: function (value) {
  99957. this._captureInterFrameTime = value;
  99958. },
  99959. enumerable: true,
  99960. configurable: true
  99961. });
  99962. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  99963. /**
  99964. * Gets the perf counter used for render time capture
  99965. */
  99966. get: function () {
  99967. return this._renderTime;
  99968. },
  99969. enumerable: true,
  99970. configurable: true
  99971. });
  99972. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  99973. /**
  99974. * Gets the render time capture status
  99975. */
  99976. get: function () {
  99977. return this._captureRenderTime;
  99978. },
  99979. /**
  99980. * Enable or disable the render time capture
  99981. */
  99982. set: function (value) {
  99983. var _this = this;
  99984. if (value === this._captureRenderTime) {
  99985. return;
  99986. }
  99987. this._captureRenderTime = value;
  99988. if (value) {
  99989. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  99990. _this._renderTime.beginMonitoring();
  99991. BABYLON.Tools.StartPerformanceCounter("Main render");
  99992. });
  99993. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  99994. _this._renderTime.endMonitoring(false);
  99995. BABYLON.Tools.EndPerformanceCounter("Main render");
  99996. });
  99997. }
  99998. else {
  99999. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100000. this._onBeforeDrawPhaseObserver = null;
  100001. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100002. this._onAfterDrawPhaseObserver = null;
  100003. }
  100004. },
  100005. enumerable: true,
  100006. configurable: true
  100007. });
  100008. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  100009. /**
  100010. * Gets the perf counter used for camera render time capture
  100011. */
  100012. get: function () {
  100013. return this._cameraRenderTime;
  100014. },
  100015. enumerable: true,
  100016. configurable: true
  100017. });
  100018. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  100019. /**
  100020. * Gets the camera render time capture status
  100021. */
  100022. get: function () {
  100023. return this._captureCameraRenderTime;
  100024. },
  100025. /**
  100026. * Enable or disable the camera render time capture
  100027. */
  100028. set: function (value) {
  100029. var _this = this;
  100030. if (value === this._captureCameraRenderTime) {
  100031. return;
  100032. }
  100033. this._captureCameraRenderTime = value;
  100034. if (value) {
  100035. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  100036. _this._cameraRenderTime.beginMonitoring();
  100037. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  100038. });
  100039. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  100040. _this._cameraRenderTime.endMonitoring(false);
  100041. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  100042. });
  100043. }
  100044. else {
  100045. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100046. this._onBeforeCameraRenderObserver = null;
  100047. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100048. this._onAfterCameraRenderObserver = null;
  100049. }
  100050. },
  100051. enumerable: true,
  100052. configurable: true
  100053. });
  100054. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  100055. /**
  100056. * Gets the perf counter used for draw calls
  100057. */
  100058. get: function () {
  100059. return this.scene.getEngine()._drawCalls;
  100060. },
  100061. enumerable: true,
  100062. configurable: true
  100063. });
  100064. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  100065. /**
  100066. * Gets the perf counter used for texture collisions
  100067. */
  100068. get: function () {
  100069. return this.scene.getEngine()._textureCollisions;
  100070. },
  100071. enumerable: true,
  100072. configurable: true
  100073. });
  100074. SceneInstrumentation.prototype.dispose = function () {
  100075. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100076. this._onAfterRenderObserver = null;
  100077. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100078. this._onBeforeActiveMeshesEvaluationObserver = null;
  100079. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100080. this._onAfterActiveMeshesEvaluationObserver = null;
  100081. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100082. this._onBeforeRenderTargetsRenderObserver = null;
  100083. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100084. this._onAfterRenderTargetsRenderObserver = null;
  100085. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  100086. this._onBeforeAnimationsObserver = null;
  100087. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100088. this._onBeforeParticlesRenderingObserver = null;
  100089. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100090. this._onAfterParticlesRenderingObserver = null;
  100091. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100092. this._onBeforeSpritesRenderingObserver = null;
  100093. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100094. this._onAfterSpritesRenderingObserver = null;
  100095. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100096. this._onBeforeDrawPhaseObserver = null;
  100097. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100098. this._onAfterDrawPhaseObserver = null;
  100099. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100100. this._onBeforePhysicsObserver = null;
  100101. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100102. this._onAfterPhysicsObserver = null;
  100103. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100104. this._onAfterAnimationsObserver = null;
  100105. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100106. this._onBeforeCameraRenderObserver = null;
  100107. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100108. this._onAfterCameraRenderObserver = null;
  100109. this.scene = null;
  100110. };
  100111. return SceneInstrumentation;
  100112. }());
  100113. BABYLON.SceneInstrumentation = SceneInstrumentation;
  100114. })(BABYLON || (BABYLON = {}));
  100115. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  100116. var BABYLON;
  100117. (function (BABYLON) {
  100118. /**
  100119. * @hidden
  100120. **/
  100121. var _TimeToken = /** @class */ (function () {
  100122. function _TimeToken() {
  100123. this._timeElapsedQueryEnded = false;
  100124. }
  100125. return _TimeToken;
  100126. }());
  100127. BABYLON._TimeToken = _TimeToken;
  100128. })(BABYLON || (BABYLON = {}));
  100129. //# sourceMappingURL=babylon.timeToken.js.map
  100130. var BABYLON;
  100131. (function (BABYLON) {
  100132. /**
  100133. * Background material defines definition.
  100134. * @hidden Mainly internal Use
  100135. */
  100136. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  100137. __extends(BackgroundMaterialDefines, _super);
  100138. /**
  100139. * Constructor of the defines.
  100140. */
  100141. function BackgroundMaterialDefines() {
  100142. var _this = _super.call(this) || this;
  100143. /**
  100144. * True if the diffuse texture is in use.
  100145. */
  100146. _this.DIFFUSE = false;
  100147. /**
  100148. * The direct UV channel to use.
  100149. */
  100150. _this.DIFFUSEDIRECTUV = 0;
  100151. /**
  100152. * True if the diffuse texture is in gamma space.
  100153. */
  100154. _this.GAMMADIFFUSE = false;
  100155. /**
  100156. * True if the diffuse texture has opacity in the alpha channel.
  100157. */
  100158. _this.DIFFUSEHASALPHA = false;
  100159. /**
  100160. * True if you want the material to fade to transparent at grazing angle.
  100161. */
  100162. _this.OPACITYFRESNEL = false;
  100163. /**
  100164. * True if an extra blur needs to be added in the reflection.
  100165. */
  100166. _this.REFLECTIONBLUR = false;
  100167. /**
  100168. * True if you want the material to fade to reflection at grazing angle.
  100169. */
  100170. _this.REFLECTIONFRESNEL = false;
  100171. /**
  100172. * True if you want the material to falloff as far as you move away from the scene center.
  100173. */
  100174. _this.REFLECTIONFALLOFF = false;
  100175. /**
  100176. * False if the current Webgl implementation does not support the texture lod extension.
  100177. */
  100178. _this.TEXTURELODSUPPORT = false;
  100179. /**
  100180. * True to ensure the data are premultiplied.
  100181. */
  100182. _this.PREMULTIPLYALPHA = false;
  100183. /**
  100184. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  100185. */
  100186. _this.USERGBCOLOR = false;
  100187. /**
  100188. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  100189. * stays aligned with the desired configuration.
  100190. */
  100191. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  100192. /**
  100193. * True to add noise in order to reduce the banding effect.
  100194. */
  100195. _this.NOISE = false;
  100196. /**
  100197. * is the reflection texture in BGR color scheme?
  100198. * Mainly used to solve a bug in ios10 video tag
  100199. */
  100200. _this.REFLECTIONBGR = false;
  100201. _this.IMAGEPROCESSING = false;
  100202. _this.VIGNETTE = false;
  100203. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  100204. _this.VIGNETTEBLENDMODEOPAQUE = false;
  100205. _this.TONEMAPPING = false;
  100206. _this.CONTRAST = false;
  100207. _this.COLORCURVES = false;
  100208. _this.COLORGRADING = false;
  100209. _this.COLORGRADING3D = false;
  100210. _this.SAMPLER3DGREENDEPTH = false;
  100211. _this.SAMPLER3DBGRMAP = false;
  100212. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  100213. _this.EXPOSURE = false;
  100214. // Reflection.
  100215. _this.REFLECTION = false;
  100216. _this.REFLECTIONMAP_3D = false;
  100217. _this.REFLECTIONMAP_SPHERICAL = false;
  100218. _this.REFLECTIONMAP_PLANAR = false;
  100219. _this.REFLECTIONMAP_CUBIC = false;
  100220. _this.REFLECTIONMAP_PROJECTION = false;
  100221. _this.REFLECTIONMAP_SKYBOX = false;
  100222. _this.REFLECTIONMAP_EXPLICIT = false;
  100223. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100224. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100225. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100226. _this.INVERTCUBICMAP = false;
  100227. _this.REFLECTIONMAP_OPPOSITEZ = false;
  100228. _this.LODINREFLECTIONALPHA = false;
  100229. _this.GAMMAREFLECTION = false;
  100230. _this.RGBDREFLECTION = false;
  100231. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  100232. // Default BJS.
  100233. _this.MAINUV1 = false;
  100234. _this.MAINUV2 = false;
  100235. _this.UV1 = false;
  100236. _this.UV2 = false;
  100237. _this.CLIPPLANE = false;
  100238. _this.POINTSIZE = false;
  100239. _this.FOG = false;
  100240. _this.NORMAL = false;
  100241. _this.NUM_BONE_INFLUENCERS = 0;
  100242. _this.BonesPerMesh = 0;
  100243. _this.INSTANCES = false;
  100244. _this.SHADOWFLOAT = false;
  100245. _this.rebuild();
  100246. return _this;
  100247. }
  100248. return BackgroundMaterialDefines;
  100249. }(BABYLON.MaterialDefines));
  100250. /**
  100251. * Background material used to create an efficient environement around your scene.
  100252. */
  100253. var BackgroundMaterial = /** @class */ (function (_super) {
  100254. __extends(BackgroundMaterial, _super);
  100255. /**
  100256. * Instantiates a Background Material in the given scene
  100257. * @param name The friendly name of the material
  100258. * @param scene The scene to add the material to
  100259. */
  100260. function BackgroundMaterial(name, scene) {
  100261. var _this = _super.call(this, name, scene) || this;
  100262. /**
  100263. * Key light Color (multiply against the environement texture)
  100264. */
  100265. _this.primaryColor = BABYLON.Color3.White();
  100266. _this._primaryColorShadowLevel = 0;
  100267. _this._primaryColorHighlightLevel = 0;
  100268. /**
  100269. * Reflection Texture used in the material.
  100270. * Should be author in a specific way for the best result (refer to the documentation).
  100271. */
  100272. _this.reflectionTexture = null;
  100273. /**
  100274. * Reflection Texture level of blur.
  100275. *
  100276. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  100277. * texture twice.
  100278. */
  100279. _this.reflectionBlur = 0;
  100280. /**
  100281. * Diffuse Texture used in the material.
  100282. * Should be author in a specific way for the best result (refer to the documentation).
  100283. */
  100284. _this.diffuseTexture = null;
  100285. _this._shadowLights = null;
  100286. /**
  100287. * Specify the list of lights casting shadow on the material.
  100288. * All scene shadow lights will be included if null.
  100289. */
  100290. _this.shadowLights = null;
  100291. /**
  100292. * Helps adjusting the shadow to a softer level if required.
  100293. * 0 means black shadows and 1 means no shadows.
  100294. */
  100295. _this.shadowLevel = 0;
  100296. /**
  100297. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  100298. * It is usually zero but might be interesting to modify according to your setup.
  100299. */
  100300. _this.sceneCenter = BABYLON.Vector3.Zero();
  100301. /**
  100302. * This helps specifying that the material is falling off to the sky box at grazing angle.
  100303. * This helps ensuring a nice transition when the camera goes under the ground.
  100304. */
  100305. _this.opacityFresnel = true;
  100306. /**
  100307. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  100308. * This helps adding a mirror texture on the ground.
  100309. */
  100310. _this.reflectionFresnel = false;
  100311. /**
  100312. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  100313. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  100314. */
  100315. _this.reflectionFalloffDistance = 0.0;
  100316. /**
  100317. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  100318. */
  100319. _this.reflectionAmount = 1.0;
  100320. /**
  100321. * This specifies the weight of the reflection at grazing angle.
  100322. */
  100323. _this.reflectionReflectance0 = 0.05;
  100324. /**
  100325. * This specifies the weight of the reflection at a perpendicular point of view.
  100326. */
  100327. _this.reflectionReflectance90 = 0.5;
  100328. /**
  100329. * Helps to directly use the maps channels instead of their level.
  100330. */
  100331. _this.useRGBColor = true;
  100332. /**
  100333. * This helps reducing the banding effect that could occur on the background.
  100334. */
  100335. _this.enableNoise = false;
  100336. _this._fovMultiplier = 1.0;
  100337. /**
  100338. * Enable the FOV adjustment feature controlled by fovMultiplier.
  100339. */
  100340. _this.useEquirectangularFOV = false;
  100341. _this._maxSimultaneousLights = 4;
  100342. /**
  100343. * Number of Simultaneous lights allowed on the material.
  100344. */
  100345. _this.maxSimultaneousLights = 4;
  100346. /**
  100347. * Keep track of the image processing observer to allow dispose and replace.
  100348. */
  100349. _this._imageProcessingObserver = null;
  100350. /**
  100351. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  100352. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  100353. */
  100354. _this.switchToBGR = false;
  100355. // Temp values kept as cache in the material.
  100356. _this._renderTargets = new BABYLON.SmartArray(16);
  100357. _this._reflectionControls = BABYLON.Vector4.Zero();
  100358. _this._white = BABYLON.Color3.White();
  100359. _this._primaryShadowColor = BABYLON.Color3.Black();
  100360. _this._primaryHighlightColor = BABYLON.Color3.Black();
  100361. // Setup the default processing configuration to the scene.
  100362. _this._attachImageProcessingConfiguration(null);
  100363. _this.getRenderTargetTextures = function () {
  100364. _this._renderTargets.reset();
  100365. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  100366. _this._renderTargets.push(_this._diffuseTexture);
  100367. }
  100368. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  100369. _this._renderTargets.push(_this._reflectionTexture);
  100370. }
  100371. return _this._renderTargets;
  100372. };
  100373. return _this;
  100374. }
  100375. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  100376. /**
  100377. * Experimental Internal Use Only.
  100378. *
  100379. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  100380. * This acts as a helper to set the primary color to a more "human friendly" value.
  100381. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  100382. * output color as close as possible from the chosen value.
  100383. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  100384. * part of lighting setup.)
  100385. */
  100386. get: function () {
  100387. return this.__perceptualColor;
  100388. },
  100389. set: function (value) {
  100390. this.__perceptualColor = value;
  100391. this._computePrimaryColorFromPerceptualColor();
  100392. this._markAllSubMeshesAsLightsDirty();
  100393. },
  100394. enumerable: true,
  100395. configurable: true
  100396. });
  100397. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  100398. /**
  100399. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  100400. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  100401. */
  100402. get: function () {
  100403. return this._primaryColorShadowLevel;
  100404. },
  100405. set: function (value) {
  100406. this._primaryColorShadowLevel = value;
  100407. this._computePrimaryColors();
  100408. this._markAllSubMeshesAsLightsDirty();
  100409. },
  100410. enumerable: true,
  100411. configurable: true
  100412. });
  100413. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  100414. /**
  100415. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  100416. * The primary color is used at the level chosen to define what the white area would look.
  100417. */
  100418. get: function () {
  100419. return this._primaryColorHighlightLevel;
  100420. },
  100421. set: function (value) {
  100422. this._primaryColorHighlightLevel = value;
  100423. this._computePrimaryColors();
  100424. this._markAllSubMeshesAsLightsDirty();
  100425. },
  100426. enumerable: true,
  100427. configurable: true
  100428. });
  100429. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  100430. /**
  100431. * Sets the reflection reflectance fresnel values according to the default standard
  100432. * empirically know to work well :-)
  100433. */
  100434. set: function (value) {
  100435. var reflectionWeight = value;
  100436. if (reflectionWeight < 0.5) {
  100437. reflectionWeight = reflectionWeight * 2.0;
  100438. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  100439. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  100440. }
  100441. else {
  100442. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  100443. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  100444. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  100445. }
  100446. },
  100447. enumerable: true,
  100448. configurable: true
  100449. });
  100450. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  100451. /**
  100452. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100453. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  100454. * Recommended to be keep at 1.0 except for special cases.
  100455. */
  100456. get: function () {
  100457. return this._fovMultiplier;
  100458. },
  100459. set: function (value) {
  100460. if (isNaN(value)) {
  100461. value = 1.0;
  100462. }
  100463. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  100464. },
  100465. enumerable: true,
  100466. configurable: true
  100467. });
  100468. /**
  100469. * Attaches a new image processing configuration to the PBR Material.
  100470. * @param configuration (if null the scene configuration will be use)
  100471. */
  100472. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  100473. var _this = this;
  100474. if (configuration === this._imageProcessingConfiguration) {
  100475. return;
  100476. }
  100477. // Detaches observer.
  100478. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100479. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100480. }
  100481. // Pick the scene configuration if needed.
  100482. if (!configuration) {
  100483. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  100484. }
  100485. else {
  100486. this._imageProcessingConfiguration = configuration;
  100487. }
  100488. // Attaches observer.
  100489. if (this._imageProcessingConfiguration) {
  100490. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  100491. _this._computePrimaryColorFromPerceptualColor();
  100492. _this._markAllSubMeshesAsImageProcessingDirty();
  100493. });
  100494. }
  100495. };
  100496. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  100497. /**
  100498. * Gets the image processing configuration used either in this material.
  100499. */
  100500. get: function () {
  100501. return this._imageProcessingConfiguration;
  100502. },
  100503. /**
  100504. * Sets the Default image processing configuration used either in the this material.
  100505. *
  100506. * If sets to null, the scene one is in use.
  100507. */
  100508. set: function (value) {
  100509. this._attachImageProcessingConfiguration(value);
  100510. // Ensure the effect will be rebuilt.
  100511. this._markAllSubMeshesAsTexturesDirty();
  100512. },
  100513. enumerable: true,
  100514. configurable: true
  100515. });
  100516. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  100517. /**
  100518. * Gets wether the color curves effect is enabled.
  100519. */
  100520. get: function () {
  100521. return this.imageProcessingConfiguration.colorCurvesEnabled;
  100522. },
  100523. /**
  100524. * Sets wether the color curves effect is enabled.
  100525. */
  100526. set: function (value) {
  100527. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  100528. },
  100529. enumerable: true,
  100530. configurable: true
  100531. });
  100532. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  100533. /**
  100534. * Gets wether the color grading effect is enabled.
  100535. */
  100536. get: function () {
  100537. return this.imageProcessingConfiguration.colorGradingEnabled;
  100538. },
  100539. /**
  100540. * Gets wether the color grading effect is enabled.
  100541. */
  100542. set: function (value) {
  100543. this.imageProcessingConfiguration.colorGradingEnabled = value;
  100544. },
  100545. enumerable: true,
  100546. configurable: true
  100547. });
  100548. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  100549. /**
  100550. * Gets wether tonemapping is enabled or not.
  100551. */
  100552. get: function () {
  100553. return this._imageProcessingConfiguration.toneMappingEnabled;
  100554. },
  100555. /**
  100556. * Sets wether tonemapping is enabled or not
  100557. */
  100558. set: function (value) {
  100559. this._imageProcessingConfiguration.toneMappingEnabled = value;
  100560. },
  100561. enumerable: true,
  100562. configurable: true
  100563. });
  100564. ;
  100565. ;
  100566. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  100567. /**
  100568. * The camera exposure used on this material.
  100569. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100570. * This corresponds to a photographic exposure.
  100571. */
  100572. get: function () {
  100573. return this._imageProcessingConfiguration.exposure;
  100574. },
  100575. /**
  100576. * The camera exposure used on this material.
  100577. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100578. * This corresponds to a photographic exposure.
  100579. */
  100580. set: function (value) {
  100581. this._imageProcessingConfiguration.exposure = value;
  100582. },
  100583. enumerable: true,
  100584. configurable: true
  100585. });
  100586. ;
  100587. ;
  100588. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  100589. /**
  100590. * Gets The camera contrast used on this material.
  100591. */
  100592. get: function () {
  100593. return this._imageProcessingConfiguration.contrast;
  100594. },
  100595. /**
  100596. * Sets The camera contrast used on this material.
  100597. */
  100598. set: function (value) {
  100599. this._imageProcessingConfiguration.contrast = value;
  100600. },
  100601. enumerable: true,
  100602. configurable: true
  100603. });
  100604. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  100605. /**
  100606. * Gets the Color Grading 2D Lookup Texture.
  100607. */
  100608. get: function () {
  100609. return this._imageProcessingConfiguration.colorGradingTexture;
  100610. },
  100611. /**
  100612. * Sets the Color Grading 2D Lookup Texture.
  100613. */
  100614. set: function (value) {
  100615. this.imageProcessingConfiguration.colorGradingTexture = value;
  100616. },
  100617. enumerable: true,
  100618. configurable: true
  100619. });
  100620. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  100621. /**
  100622. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100623. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100624. * 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;
  100625. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100626. */
  100627. get: function () {
  100628. return this.imageProcessingConfiguration.colorCurves;
  100629. },
  100630. /**
  100631. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100632. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100633. * 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;
  100634. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100635. */
  100636. set: function (value) {
  100637. this.imageProcessingConfiguration.colorCurves = value;
  100638. },
  100639. enumerable: true,
  100640. configurable: true
  100641. });
  100642. /**
  100643. * The entire material has been created in order to prevent overdraw.
  100644. * @returns false
  100645. */
  100646. BackgroundMaterial.prototype.needAlphaTesting = function () {
  100647. return true;
  100648. };
  100649. /**
  100650. * The entire material has been created in order to prevent overdraw.
  100651. * @returns true if blending is enable
  100652. */
  100653. BackgroundMaterial.prototype.needAlphaBlending = function () {
  100654. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  100655. };
  100656. /**
  100657. * Checks wether the material is ready to be rendered for a given mesh.
  100658. * @param mesh The mesh to render
  100659. * @param subMesh The submesh to check against
  100660. * @param useInstances Specify wether or not the material is used with instances
  100661. * @returns true if all the dependencies are ready (Textures, Effects...)
  100662. */
  100663. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  100664. var _this = this;
  100665. if (useInstances === void 0) { useInstances = false; }
  100666. if (subMesh.effect && this.isFrozen) {
  100667. if (this._wasPreviouslyReady) {
  100668. return true;
  100669. }
  100670. }
  100671. if (!subMesh._materialDefines) {
  100672. subMesh._materialDefines = new BackgroundMaterialDefines();
  100673. }
  100674. var scene = this.getScene();
  100675. var defines = subMesh._materialDefines;
  100676. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  100677. if (defines._renderId === scene.getRenderId()) {
  100678. return true;
  100679. }
  100680. }
  100681. var engine = scene.getEngine();
  100682. // Lights
  100683. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  100684. defines._needNormals = true;
  100685. // Textures
  100686. if (defines._areTexturesDirty) {
  100687. defines._needUVs = false;
  100688. if (scene.texturesEnabled) {
  100689. if (scene.getEngine().getCaps().textureLOD) {
  100690. defines.TEXTURELODSUPPORT = true;
  100691. }
  100692. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100693. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  100694. return false;
  100695. }
  100696. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  100697. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  100698. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  100699. defines.OPACITYFRESNEL = this._opacityFresnel;
  100700. }
  100701. else {
  100702. defines.DIFFUSE = false;
  100703. defines.DIFFUSEHASALPHA = false;
  100704. defines.GAMMADIFFUSE = false;
  100705. defines.OPACITYFRESNEL = false;
  100706. }
  100707. var reflectionTexture = this._reflectionTexture;
  100708. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100709. if (!reflectionTexture.isReadyOrNotBlocking()) {
  100710. return false;
  100711. }
  100712. defines.REFLECTION = true;
  100713. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  100714. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  100715. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  100716. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  100717. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  100718. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  100719. defines.REFLECTIONBGR = this.switchToBGR;
  100720. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  100721. defines.INVERTCUBICMAP = true;
  100722. }
  100723. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  100724. switch (reflectionTexture.coordinatesMode) {
  100725. case BABYLON.Texture.EXPLICIT_MODE:
  100726. defines.REFLECTIONMAP_EXPLICIT = true;
  100727. break;
  100728. case BABYLON.Texture.PLANAR_MODE:
  100729. defines.REFLECTIONMAP_PLANAR = true;
  100730. break;
  100731. case BABYLON.Texture.PROJECTION_MODE:
  100732. defines.REFLECTIONMAP_PROJECTION = true;
  100733. break;
  100734. case BABYLON.Texture.SKYBOX_MODE:
  100735. defines.REFLECTIONMAP_SKYBOX = true;
  100736. break;
  100737. case BABYLON.Texture.SPHERICAL_MODE:
  100738. defines.REFLECTIONMAP_SPHERICAL = true;
  100739. break;
  100740. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  100741. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  100742. break;
  100743. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  100744. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  100745. break;
  100746. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  100747. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  100748. break;
  100749. case BABYLON.Texture.CUBIC_MODE:
  100750. case BABYLON.Texture.INVCUBIC_MODE:
  100751. default:
  100752. defines.REFLECTIONMAP_CUBIC = true;
  100753. break;
  100754. }
  100755. if (this.reflectionFresnel) {
  100756. defines.REFLECTIONFRESNEL = true;
  100757. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  100758. this._reflectionControls.x = this.reflectionAmount;
  100759. this._reflectionControls.y = this.reflectionReflectance0;
  100760. this._reflectionControls.z = this.reflectionReflectance90;
  100761. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  100762. }
  100763. else {
  100764. defines.REFLECTIONFRESNEL = false;
  100765. defines.REFLECTIONFALLOFF = false;
  100766. }
  100767. }
  100768. else {
  100769. defines.REFLECTION = false;
  100770. defines.REFLECTIONFRESNEL = false;
  100771. defines.REFLECTIONFALLOFF = false;
  100772. defines.REFLECTIONBLUR = false;
  100773. defines.REFLECTIONMAP_3D = false;
  100774. defines.REFLECTIONMAP_SPHERICAL = false;
  100775. defines.REFLECTIONMAP_PLANAR = false;
  100776. defines.REFLECTIONMAP_CUBIC = false;
  100777. defines.REFLECTIONMAP_PROJECTION = false;
  100778. defines.REFLECTIONMAP_SKYBOX = false;
  100779. defines.REFLECTIONMAP_EXPLICIT = false;
  100780. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100781. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100782. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100783. defines.INVERTCUBICMAP = false;
  100784. defines.REFLECTIONMAP_OPPOSITEZ = false;
  100785. defines.LODINREFLECTIONALPHA = false;
  100786. defines.GAMMAREFLECTION = false;
  100787. defines.RGBDREFLECTION = false;
  100788. }
  100789. }
  100790. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  100791. defines.USERGBCOLOR = this._useRGBColor;
  100792. defines.NOISE = this._enableNoise;
  100793. }
  100794. if (defines._areLightsDirty) {
  100795. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  100796. }
  100797. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  100798. if (!this._imageProcessingConfiguration.isReady()) {
  100799. return false;
  100800. }
  100801. this._imageProcessingConfiguration.prepareDefines(defines);
  100802. }
  100803. // Misc.
  100804. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  100805. // Values that need to be evaluated on every frame
  100806. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  100807. // Attribs
  100808. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  100809. if (mesh) {
  100810. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100811. mesh.createNormals(true);
  100812. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  100813. }
  100814. }
  100815. }
  100816. // Get correct effect
  100817. if (defines.isDirty) {
  100818. defines.markAsProcessed();
  100819. scene.resetCachedMaterial();
  100820. // Fallbacks
  100821. var fallbacks = new BABYLON.EffectFallbacks();
  100822. if (defines.FOG) {
  100823. fallbacks.addFallback(0, "FOG");
  100824. }
  100825. if (defines.POINTSIZE) {
  100826. fallbacks.addFallback(1, "POINTSIZE");
  100827. }
  100828. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  100829. if (defines.NUM_BONE_INFLUENCERS > 0) {
  100830. fallbacks.addCPUSkinningFallback(0, mesh);
  100831. }
  100832. //Attributes
  100833. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100834. if (defines.NORMAL) {
  100835. attribs.push(BABYLON.VertexBuffer.NormalKind);
  100836. }
  100837. if (defines.UV1) {
  100838. attribs.push(BABYLON.VertexBuffer.UVKind);
  100839. }
  100840. if (defines.UV2) {
  100841. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100842. }
  100843. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  100844. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  100845. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  100846. "vFogInfos", "vFogColor", "pointSize",
  100847. "vClipPlane", "mBones",
  100848. "vPrimaryColor", "vPrimaryColorShadow",
  100849. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  100850. "shadowLevel", "alpha",
  100851. "vBackgroundCenter", "vReflectionControl",
  100852. "vDiffuseInfos", "diffuseMatrix",
  100853. ];
  100854. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  100855. var uniformBuffers = ["Material", "Scene"];
  100856. if (BABYLON.ImageProcessingConfiguration) {
  100857. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  100858. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  100859. }
  100860. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  100861. uniformsNames: uniforms,
  100862. uniformBuffersNames: uniformBuffers,
  100863. samplers: samplers,
  100864. defines: defines,
  100865. maxSimultaneousLights: this._maxSimultaneousLights
  100866. });
  100867. var onCompiled = function (effect) {
  100868. if (_this.onCompiled) {
  100869. _this.onCompiled(effect);
  100870. }
  100871. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  100872. };
  100873. var join = defines.toString();
  100874. subMesh.setEffect(scene.getEngine().createEffect("background", {
  100875. attributes: attribs,
  100876. uniformsNames: uniforms,
  100877. uniformBuffersNames: uniformBuffers,
  100878. samplers: samplers,
  100879. defines: join,
  100880. fallbacks: fallbacks,
  100881. onCompiled: onCompiled,
  100882. onError: this.onError,
  100883. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  100884. }, engine), defines);
  100885. this.buildUniformLayout();
  100886. }
  100887. if (!subMesh.effect || !subMesh.effect.isReady()) {
  100888. return false;
  100889. }
  100890. defines._renderId = scene.getRenderId();
  100891. this._wasPreviouslyReady = true;
  100892. return true;
  100893. };
  100894. /**
  100895. * Compute the primary color according to the chosen perceptual color.
  100896. */
  100897. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  100898. if (!this.__perceptualColor) {
  100899. return;
  100900. }
  100901. this._primaryColor.copyFrom(this.__perceptualColor);
  100902. // Revert gamma space.
  100903. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  100904. // Revert image processing configuration.
  100905. if (this._imageProcessingConfiguration) {
  100906. // Revert Exposure.
  100907. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  100908. }
  100909. this._computePrimaryColors();
  100910. };
  100911. /**
  100912. * Compute the highlights and shadow colors according to their chosen levels.
  100913. */
  100914. BackgroundMaterial.prototype._computePrimaryColors = function () {
  100915. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  100916. return;
  100917. }
  100918. // Find the highlight color based on the configuration.
  100919. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  100920. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  100921. // Find the shadow color based on the configuration.
  100922. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  100923. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  100924. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  100925. };
  100926. /**
  100927. * Build the uniform buffer used in the material.
  100928. */
  100929. BackgroundMaterial.prototype.buildUniformLayout = function () {
  100930. // Order is important !
  100931. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  100932. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  100933. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  100934. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  100935. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  100936. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  100937. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  100938. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  100939. this._uniformBuffer.addUniform("pointSize", 1);
  100940. this._uniformBuffer.addUniform("shadowLevel", 1);
  100941. this._uniformBuffer.addUniform("alpha", 1);
  100942. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  100943. this._uniformBuffer.addUniform("vReflectionControl", 4);
  100944. this._uniformBuffer.create();
  100945. };
  100946. /**
  100947. * Unbind the material.
  100948. */
  100949. BackgroundMaterial.prototype.unbind = function () {
  100950. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  100951. this._uniformBuffer.setTexture("diffuseSampler", null);
  100952. }
  100953. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  100954. this._uniformBuffer.setTexture("reflectionSampler", null);
  100955. }
  100956. _super.prototype.unbind.call(this);
  100957. };
  100958. /**
  100959. * Bind only the world matrix to the material.
  100960. * @param world The world matrix to bind.
  100961. */
  100962. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  100963. this._activeEffect.setMatrix("world", world);
  100964. };
  100965. /**
  100966. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  100967. * @param world The world matrix to bind.
  100968. * @param subMesh The submesh to bind for.
  100969. */
  100970. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  100971. var scene = this.getScene();
  100972. var defines = subMesh._materialDefines;
  100973. if (!defines) {
  100974. return;
  100975. }
  100976. var effect = subMesh.effect;
  100977. if (!effect) {
  100978. return;
  100979. }
  100980. this._activeEffect = effect;
  100981. // Matrices
  100982. this.bindOnlyWorldMatrix(world);
  100983. // Bones
  100984. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  100985. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  100986. if (mustRebind) {
  100987. this._uniformBuffer.bindToEffect(effect, "Material");
  100988. this.bindViewProjection(effect);
  100989. var reflectionTexture = this._reflectionTexture;
  100990. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  100991. // Texture uniforms
  100992. if (scene.texturesEnabled) {
  100993. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100994. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  100995. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  100996. }
  100997. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100998. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  100999. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  101000. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  101001. }
  101002. }
  101003. if (this.shadowLevel > 0) {
  101004. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  101005. }
  101006. this._uniformBuffer.updateFloat("alpha", this.alpha);
  101007. // Point size
  101008. if (this.pointsCloud) {
  101009. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  101010. }
  101011. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  101012. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  101013. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  101014. }
  101015. else {
  101016. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  101017. }
  101018. }
  101019. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  101020. // Textures
  101021. if (scene.texturesEnabled) {
  101022. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101023. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  101024. }
  101025. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101026. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  101027. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101028. }
  101029. else if (!defines.REFLECTIONBLUR) {
  101030. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101031. }
  101032. else {
  101033. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  101034. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  101035. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  101036. }
  101037. if (defines.REFLECTIONFRESNEL) {
  101038. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  101039. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  101040. }
  101041. }
  101042. }
  101043. // Clip plane
  101044. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  101045. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  101046. }
  101047. if (mustRebind || !this.isFrozen) {
  101048. if (scene.lightsEnabled) {
  101049. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  101050. }
  101051. // View
  101052. this.bindView(effect);
  101053. // Fog
  101054. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  101055. // image processing
  101056. if (this._imageProcessingConfiguration) {
  101057. this._imageProcessingConfiguration.bind(this._activeEffect);
  101058. }
  101059. }
  101060. this._uniformBuffer.update();
  101061. this._afterBind(mesh, this._activeEffect);
  101062. };
  101063. /**
  101064. * Dispose the material.
  101065. * @param forceDisposeEffect Force disposal of the associated effect.
  101066. * @param forceDisposeTextures Force disposal of the associated textures.
  101067. */
  101068. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  101069. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  101070. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  101071. if (forceDisposeTextures) {
  101072. if (this.diffuseTexture) {
  101073. this.diffuseTexture.dispose();
  101074. }
  101075. if (this.reflectionTexture) {
  101076. this.reflectionTexture.dispose();
  101077. }
  101078. }
  101079. this._renderTargets.dispose();
  101080. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101081. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101082. }
  101083. _super.prototype.dispose.call(this, forceDisposeEffect);
  101084. };
  101085. /**
  101086. * Clones the material.
  101087. * @param name The cloned name.
  101088. * @returns The cloned material.
  101089. */
  101090. BackgroundMaterial.prototype.clone = function (name) {
  101091. var _this = this;
  101092. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  101093. };
  101094. /**
  101095. * Serializes the current material to its JSON representation.
  101096. * @returns The JSON representation.
  101097. */
  101098. BackgroundMaterial.prototype.serialize = function () {
  101099. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101100. serializationObject.customType = "BABYLON.BackgroundMaterial";
  101101. return serializationObject;
  101102. };
  101103. /**
  101104. * Gets the class name of the material
  101105. * @returns "BackgroundMaterial"
  101106. */
  101107. BackgroundMaterial.prototype.getClassName = function () {
  101108. return "BackgroundMaterial";
  101109. };
  101110. /**
  101111. * Parse a JSON input to create back a background material.
  101112. * @param source The JSON data to parse
  101113. * @param scene The scene to create the parsed material in
  101114. * @param rootUrl The root url of the assets the material depends upon
  101115. * @returns the instantiated BackgroundMaterial.
  101116. */
  101117. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  101118. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  101119. };
  101120. /**
  101121. * Standard reflectance value at parallel view angle.
  101122. */
  101123. BackgroundMaterial.StandardReflectance0 = 0.05;
  101124. /**
  101125. * Standard reflectance value at grazing angle.
  101126. */
  101127. BackgroundMaterial.StandardReflectance90 = 0.5;
  101128. __decorate([
  101129. BABYLON.serializeAsColor3()
  101130. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  101131. __decorate([
  101132. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101133. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  101134. __decorate([
  101135. BABYLON.serializeAsColor3()
  101136. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  101137. __decorate([
  101138. BABYLON.serialize()
  101139. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  101140. __decorate([
  101141. BABYLON.serialize()
  101142. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  101143. __decorate([
  101144. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101145. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  101146. __decorate([
  101147. BABYLON.serializeAsTexture()
  101148. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  101149. __decorate([
  101150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101151. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  101152. __decorate([
  101153. BABYLON.serialize()
  101154. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  101155. __decorate([
  101156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101157. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  101158. __decorate([
  101159. BABYLON.serializeAsTexture()
  101160. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  101161. __decorate([
  101162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101163. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  101164. __decorate([
  101165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101166. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  101167. __decorate([
  101168. BABYLON.serialize()
  101169. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  101170. __decorate([
  101171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101172. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  101173. __decorate([
  101174. BABYLON.serializeAsVector3()
  101175. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  101176. __decorate([
  101177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101178. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  101179. __decorate([
  101180. BABYLON.serialize()
  101181. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  101182. __decorate([
  101183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101184. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  101185. __decorate([
  101186. BABYLON.serialize()
  101187. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  101188. __decorate([
  101189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101190. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  101191. __decorate([
  101192. BABYLON.serialize()
  101193. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  101194. __decorate([
  101195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101196. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  101197. __decorate([
  101198. BABYLON.serialize()
  101199. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  101200. __decorate([
  101201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101202. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  101203. __decorate([
  101204. BABYLON.serialize()
  101205. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  101206. __decorate([
  101207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101208. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  101209. __decorate([
  101210. BABYLON.serialize()
  101211. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  101212. __decorate([
  101213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101214. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  101215. __decorate([
  101216. BABYLON.serialize()
  101217. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  101218. __decorate([
  101219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101220. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  101221. __decorate([
  101222. BABYLON.serialize()
  101223. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  101224. __decorate([
  101225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101226. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  101227. __decorate([
  101228. BABYLON.serialize()
  101229. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  101230. __decorate([
  101231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101232. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  101233. __decorate([
  101234. BABYLON.serializeAsImageProcessingConfiguration()
  101235. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  101236. return BackgroundMaterial;
  101237. }(BABYLON.PushMaterial));
  101238. BABYLON.BackgroundMaterial = BackgroundMaterial;
  101239. })(BABYLON || (BABYLON = {}));
  101240. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  101241. var __assign = (this && this.__assign) || Object.assign || function(t) {
  101242. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101243. s = arguments[i];
  101244. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101245. t[p] = s[p];
  101246. }
  101247. return t;
  101248. };
  101249. var BABYLON;
  101250. (function (BABYLON) {
  101251. /**
  101252. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  101253. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  101254. * It also helps with the default setup of your imageProcessing configuration.
  101255. */
  101256. var EnvironmentHelper = /** @class */ (function () {
  101257. /**
  101258. * constructor
  101259. * @param options
  101260. * @param scene The scene to add the material to
  101261. */
  101262. function EnvironmentHelper(options, scene) {
  101263. var _this = this;
  101264. this._errorHandler = function (message, exception) {
  101265. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  101266. };
  101267. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  101268. this._scene = scene;
  101269. this.onErrorObservable = new BABYLON.Observable();
  101270. this._setupBackground();
  101271. this._setupImageProcessing();
  101272. }
  101273. /**
  101274. * Creates the default options for the helper.
  101275. */
  101276. EnvironmentHelper._getDefaultOptions = function () {
  101277. return {
  101278. createGround: true,
  101279. groundSize: 15,
  101280. groundTexture: this._groundTextureCDNUrl,
  101281. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101282. groundOpacity: 0.9,
  101283. enableGroundShadow: true,
  101284. groundShadowLevel: 0.5,
  101285. enableGroundMirror: false,
  101286. groundMirrorSizeRatio: 0.3,
  101287. groundMirrorBlurKernel: 64,
  101288. groundMirrorAmount: 1,
  101289. groundMirrorFresnelWeight: 1,
  101290. groundMirrorFallOffDistance: 0,
  101291. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  101292. groundYBias: 0.00001,
  101293. createSkybox: true,
  101294. skyboxSize: 20,
  101295. skyboxTexture: this._skyboxTextureCDNUrl,
  101296. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101297. backgroundYRotation: 0,
  101298. sizeAuto: true,
  101299. rootPosition: BABYLON.Vector3.Zero(),
  101300. setupImageProcessing: true,
  101301. environmentTexture: this._environmentTextureCDNUrl,
  101302. cameraExposure: 0.8,
  101303. cameraContrast: 1.2,
  101304. toneMappingEnabled: true,
  101305. };
  101306. };
  101307. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  101308. /**
  101309. * Gets the root mesh created by the helper.
  101310. */
  101311. get: function () {
  101312. return this._rootMesh;
  101313. },
  101314. enumerable: true,
  101315. configurable: true
  101316. });
  101317. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  101318. /**
  101319. * Gets the skybox created by the helper.
  101320. */
  101321. get: function () {
  101322. return this._skybox;
  101323. },
  101324. enumerable: true,
  101325. configurable: true
  101326. });
  101327. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  101328. /**
  101329. * Gets the skybox texture created by the helper.
  101330. */
  101331. get: function () {
  101332. return this._skyboxTexture;
  101333. },
  101334. enumerable: true,
  101335. configurable: true
  101336. });
  101337. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  101338. /**
  101339. * Gets the skybox material created by the helper.
  101340. */
  101341. get: function () {
  101342. return this._skyboxMaterial;
  101343. },
  101344. enumerable: true,
  101345. configurable: true
  101346. });
  101347. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  101348. /**
  101349. * Gets the ground mesh created by the helper.
  101350. */
  101351. get: function () {
  101352. return this._ground;
  101353. },
  101354. enumerable: true,
  101355. configurable: true
  101356. });
  101357. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  101358. /**
  101359. * Gets the ground texture created by the helper.
  101360. */
  101361. get: function () {
  101362. return this._groundTexture;
  101363. },
  101364. enumerable: true,
  101365. configurable: true
  101366. });
  101367. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  101368. /**
  101369. * Gets the ground mirror created by the helper.
  101370. */
  101371. get: function () {
  101372. return this._groundMirror;
  101373. },
  101374. enumerable: true,
  101375. configurable: true
  101376. });
  101377. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  101378. /**
  101379. * Gets the ground mirror render list to helps pushing the meshes
  101380. * you wish in the ground reflection.
  101381. */
  101382. get: function () {
  101383. if (this._groundMirror) {
  101384. return this._groundMirror.renderList;
  101385. }
  101386. return null;
  101387. },
  101388. enumerable: true,
  101389. configurable: true
  101390. });
  101391. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  101392. /**
  101393. * Gets the ground material created by the helper.
  101394. */
  101395. get: function () {
  101396. return this._groundMaterial;
  101397. },
  101398. enumerable: true,
  101399. configurable: true
  101400. });
  101401. /**
  101402. * Updates the background according to the new options
  101403. * @param options
  101404. */
  101405. EnvironmentHelper.prototype.updateOptions = function (options) {
  101406. var newOptions = __assign({}, this._options, options);
  101407. if (this._ground && !newOptions.createGround) {
  101408. this._ground.dispose();
  101409. this._ground = null;
  101410. }
  101411. if (this._groundMaterial && !newOptions.createGround) {
  101412. this._groundMaterial.dispose();
  101413. this._groundMaterial = null;
  101414. }
  101415. if (this._groundTexture) {
  101416. if (this._options.groundTexture != newOptions.groundTexture) {
  101417. this._groundTexture.dispose();
  101418. this._groundTexture = null;
  101419. }
  101420. }
  101421. if (this._skybox && !newOptions.createSkybox) {
  101422. this._skybox.dispose();
  101423. this._skybox = null;
  101424. }
  101425. if (this._skyboxMaterial && !newOptions.createSkybox) {
  101426. this._skyboxMaterial.dispose();
  101427. this._skyboxMaterial = null;
  101428. }
  101429. if (this._skyboxTexture) {
  101430. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  101431. this._skyboxTexture.dispose();
  101432. this._skyboxTexture = null;
  101433. }
  101434. }
  101435. if (this._groundMirror && !newOptions.enableGroundMirror) {
  101436. this._groundMirror.dispose();
  101437. this._groundMirror = null;
  101438. }
  101439. if (this._scene.environmentTexture) {
  101440. if (this._options.environmentTexture != newOptions.environmentTexture) {
  101441. this._scene.environmentTexture.dispose();
  101442. }
  101443. }
  101444. this._options = newOptions;
  101445. this._setupBackground();
  101446. this._setupImageProcessing();
  101447. };
  101448. /**
  101449. * Sets the primary color of all the available elements.
  101450. * @param color the main color to affect to the ground and the background
  101451. */
  101452. EnvironmentHelper.prototype.setMainColor = function (color) {
  101453. if (this.groundMaterial) {
  101454. this.groundMaterial.primaryColor = color;
  101455. }
  101456. if (this.skyboxMaterial) {
  101457. this.skyboxMaterial.primaryColor = color;
  101458. }
  101459. if (this.groundMirror) {
  101460. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  101461. }
  101462. };
  101463. /**
  101464. * Setup the image processing according to the specified options.
  101465. */
  101466. EnvironmentHelper.prototype._setupImageProcessing = function () {
  101467. if (this._options.setupImageProcessing) {
  101468. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  101469. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  101470. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  101471. this._setupEnvironmentTexture();
  101472. }
  101473. };
  101474. /**
  101475. * Setup the environment texture according to the specified options.
  101476. */
  101477. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  101478. if (this._scene.environmentTexture) {
  101479. return;
  101480. }
  101481. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  101482. this._scene.environmentTexture = this._options.environmentTexture;
  101483. return;
  101484. }
  101485. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  101486. this._scene.environmentTexture = environmentTexture;
  101487. };
  101488. /**
  101489. * Setup the background according to the specified options.
  101490. */
  101491. EnvironmentHelper.prototype._setupBackground = function () {
  101492. if (!this._rootMesh) {
  101493. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  101494. }
  101495. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  101496. var sceneSize = this._getSceneSize();
  101497. if (this._options.createGround) {
  101498. this._setupGround(sceneSize);
  101499. this._setupGroundMaterial();
  101500. this._setupGroundDiffuseTexture();
  101501. if (this._options.enableGroundMirror) {
  101502. this._setupGroundMirrorTexture(sceneSize);
  101503. }
  101504. this._setupMirrorInGroundMaterial();
  101505. }
  101506. if (this._options.createSkybox) {
  101507. this._setupSkybox(sceneSize);
  101508. this._setupSkyboxMaterial();
  101509. this._setupSkyboxReflectionTexture();
  101510. }
  101511. this._rootMesh.position.x = sceneSize.rootPosition.x;
  101512. this._rootMesh.position.z = sceneSize.rootPosition.z;
  101513. this._rootMesh.position.y = sceneSize.rootPosition.y;
  101514. };
  101515. /**
  101516. * Get the scene sizes according to the setup.
  101517. */
  101518. EnvironmentHelper.prototype._getSceneSize = function () {
  101519. var _this = this;
  101520. var groundSize = this._options.groundSize;
  101521. var skyboxSize = this._options.skyboxSize;
  101522. var rootPosition = this._options.rootPosition;
  101523. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  101524. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101525. }
  101526. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  101527. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  101528. });
  101529. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  101530. if (this._options.sizeAuto) {
  101531. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  101532. this._scene.activeCamera.upperRadiusLimit) {
  101533. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  101534. skyboxSize = groundSize;
  101535. }
  101536. var sceneDiagonalLenght = sceneDiagonal.length();
  101537. if (sceneDiagonalLenght > groundSize) {
  101538. groundSize = sceneDiagonalLenght * 2;
  101539. skyboxSize = groundSize;
  101540. }
  101541. // 10 % bigger.
  101542. groundSize *= 1.1;
  101543. skyboxSize *= 1.5;
  101544. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  101545. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  101546. }
  101547. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101548. };
  101549. /**
  101550. * Setup the ground according to the specified options.
  101551. */
  101552. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  101553. var _this = this;
  101554. if (!this._ground || this._ground.isDisposed()) {
  101555. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  101556. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  101557. this._ground.parent = this._rootMesh;
  101558. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  101559. }
  101560. this._ground.receiveShadows = this._options.enableGroundShadow;
  101561. };
  101562. /**
  101563. * Setup the ground material according to the specified options.
  101564. */
  101565. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  101566. if (!this._groundMaterial) {
  101567. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  101568. }
  101569. this._groundMaterial.alpha = this._options.groundOpacity;
  101570. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  101571. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  101572. this._groundMaterial.primaryColor = this._options.groundColor;
  101573. this._groundMaterial.useRGBColor = false;
  101574. this._groundMaterial.enableNoise = true;
  101575. if (this._ground) {
  101576. this._ground.material = this._groundMaterial;
  101577. }
  101578. };
  101579. /**
  101580. * Setup the ground diffuse texture according to the specified options.
  101581. */
  101582. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  101583. if (!this._groundMaterial) {
  101584. return;
  101585. }
  101586. if (this._groundTexture) {
  101587. return;
  101588. }
  101589. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  101590. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  101591. return;
  101592. }
  101593. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101594. diffuseTexture.gammaSpace = false;
  101595. diffuseTexture.hasAlpha = true;
  101596. this._groundMaterial.diffuseTexture = diffuseTexture;
  101597. };
  101598. /**
  101599. * Setup the ground mirror texture according to the specified options.
  101600. */
  101601. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  101602. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101603. if (!this._groundMirror) {
  101604. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  101605. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  101606. this._groundMirror.anisotropicFilteringLevel = 1;
  101607. this._groundMirror.wrapU = wrapping;
  101608. this._groundMirror.wrapV = wrapping;
  101609. this._groundMirror.gammaSpace = false;
  101610. if (this._groundMirror.renderList) {
  101611. for (var i = 0; i < this._scene.meshes.length; i++) {
  101612. var mesh = this._scene.meshes[i];
  101613. if (mesh !== this._ground &&
  101614. mesh !== this._skybox &&
  101615. mesh !== this._rootMesh) {
  101616. this._groundMirror.renderList.push(mesh);
  101617. }
  101618. }
  101619. }
  101620. }
  101621. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  101622. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  101623. };
  101624. /**
  101625. * Setup the ground to receive the mirror texture.
  101626. */
  101627. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  101628. if (this._groundMaterial) {
  101629. this._groundMaterial.reflectionTexture = this._groundMirror;
  101630. this._groundMaterial.reflectionFresnel = true;
  101631. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  101632. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  101633. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  101634. }
  101635. };
  101636. /**
  101637. * Setup the skybox according to the specified options.
  101638. */
  101639. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  101640. var _this = this;
  101641. if (!this._skybox || this._skybox.isDisposed()) {
  101642. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  101643. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  101644. }
  101645. this._skybox.parent = this._rootMesh;
  101646. };
  101647. /**
  101648. * Setup the skybox material according to the specified options.
  101649. */
  101650. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  101651. if (!this._skybox) {
  101652. return;
  101653. }
  101654. if (!this._skyboxMaterial) {
  101655. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  101656. }
  101657. this._skyboxMaterial.useRGBColor = false;
  101658. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  101659. this._skyboxMaterial.enableNoise = true;
  101660. this._skybox.material = this._skyboxMaterial;
  101661. };
  101662. /**
  101663. * Setup the skybox reflection texture according to the specified options.
  101664. */
  101665. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  101666. if (!this._skyboxMaterial) {
  101667. return;
  101668. }
  101669. if (this._skyboxTexture) {
  101670. return;
  101671. }
  101672. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  101673. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  101674. return;
  101675. }
  101676. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101677. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  101678. this._skyboxTexture.gammaSpace = false;
  101679. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  101680. };
  101681. /**
  101682. * Dispose all the elements created by the Helper.
  101683. */
  101684. EnvironmentHelper.prototype.dispose = function () {
  101685. if (this._groundMaterial) {
  101686. this._groundMaterial.dispose(true, true);
  101687. }
  101688. if (this._skyboxMaterial) {
  101689. this._skyboxMaterial.dispose(true, true);
  101690. }
  101691. this._rootMesh.dispose(false);
  101692. };
  101693. /**
  101694. * Default ground texture URL.
  101695. */
  101696. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  101697. /**
  101698. * Default skybox texture URL.
  101699. */
  101700. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  101701. /**
  101702. * Default environment texture URL.
  101703. */
  101704. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  101705. return EnvironmentHelper;
  101706. }());
  101707. BABYLON.EnvironmentHelper = EnvironmentHelper;
  101708. })(BABYLON || (BABYLON = {}));
  101709. //# sourceMappingURL=babylon.environmentHelper.js.map
  101710. var BABYLON;
  101711. (function (BABYLON) {
  101712. /**
  101713. * This class is made for on one-liner static method to help creating particle systems.
  101714. */
  101715. var ParticleHelper = /** @class */ (function () {
  101716. function ParticleHelper() {
  101717. }
  101718. /**
  101719. * This is the main static method (one-liner) of this helper to create different particle systems.
  101720. * @param type This string represents the type to the particle system to create
  101721. * @param emitter The object where the particle system will start to emit from.
  101722. * @param scene The scene where the particle system should live.
  101723. * @param gpu If the system will use gpu.
  101724. * @returns the ParticleSystem created.
  101725. */
  101726. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  101727. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  101728. if (gpu === void 0) { gpu = false; }
  101729. return new Promise(function (resolve, reject) {
  101730. if (!scene) {
  101731. scene = BABYLON.Engine.LastCreatedScene;
  101732. ;
  101733. }
  101734. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  101735. return reject("Particle system with GPU is not supported.");
  101736. }
  101737. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  101738. var newData = JSON.parse(data.toString());
  101739. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  101740. }, undefined, undefined, undefined, function (req, exception) {
  101741. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  101742. });
  101743. });
  101744. };
  101745. /**
  101746. * Static function used to create a new particle system from a IParticleSystemData
  101747. * @param data defines the source data
  101748. * @param scene defines the hosting scene
  101749. * @param emitter defines the particle emitter
  101750. * @returns a new ParticleSystem based on referenced data
  101751. */
  101752. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  101753. // Create a particle system
  101754. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  101755. // Where the particles come from
  101756. system.emitter = emitter; // the starting object, the emitter
  101757. ParticleHelper.UpdateSystem(system, data, scene);
  101758. return system;
  101759. };
  101760. /**
  101761. * Static function used to update a particle system from a IParticleSystemData
  101762. * @param system defines the particle system to update
  101763. * @param data defines the source data
  101764. * @param scene defines the hosting scene
  101765. */
  101766. ParticleHelper.UpdateSystem = function (system, data, scene) {
  101767. // Texture of each particle
  101768. if (data.textureFile) {
  101769. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  101770. }
  101771. // Colors of all particles
  101772. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  101773. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  101774. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  101775. // Size of each particle (random between...
  101776. system.minSize = data.minSize;
  101777. system.maxSize = data.maxSize;
  101778. system.minScaleX = data.minScaleX;
  101779. system.maxScaleX = data.maxScaleX;
  101780. system.minScaleY = data.minScaleY;
  101781. system.maxScaleY = data.maxScaleY;
  101782. // Life time of each particle (random between...
  101783. system.minLifeTime = data.minLifeTime;
  101784. system.maxLifeTime = data.maxLifeTime;
  101785. // Emission rate
  101786. system.emitRate = data.emitRate;
  101787. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101788. system.blendMode = data.blendMode;
  101789. // Set the gravity of all particles
  101790. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  101791. // Angular speed, in radians
  101792. system.minAngularSpeed = data.minAngularSpeed;
  101793. system.maxAngularSpeed = data.maxAngularSpeed;
  101794. // Speed
  101795. system.minEmitPower = data.minEmitPower;
  101796. system.maxEmitPower = data.maxEmitPower;
  101797. system.updateSpeed = data.updateSpeed;
  101798. switch (data.emitterType) {
  101799. case "box":
  101800. if (!data.direction1 || !data.direction2) {
  101801. throw new Error("Directions are missing in this particle system.");
  101802. }
  101803. if (!data.minEmitBox || !data.maxEmitBox) {
  101804. throw new Error("EmitBox is missing in this particle system.");
  101805. }
  101806. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  101807. break;
  101808. case "sphere":
  101809. system.createSphereEmitter(data.radius);
  101810. break;
  101811. case "directed_sphere":
  101812. if (!data.direction1 || !data.direction2) {
  101813. throw new Error("Directions are missing in this particle system.");
  101814. }
  101815. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  101816. break;
  101817. case "cone":
  101818. system.createConeEmitter(data.radius, data.angle);
  101819. break;
  101820. default:
  101821. break;
  101822. }
  101823. };
  101824. /**
  101825. * Static function used to export a particle system to a IParticleSystemData variable.
  101826. * Please note that texture file name is not exported and must be added manually
  101827. * @param system defines the particle system to export
  101828. */
  101829. ParticleHelper.ExportSystem = function (system) {
  101830. var outData = {};
  101831. // Colors of all particles
  101832. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  101833. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  101834. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  101835. // Size of each particle (random between...
  101836. outData.minSize = system.minSize;
  101837. outData.maxSize = system.maxSize;
  101838. outData.minScaleX = system.minScaleX;
  101839. outData.maxScaleX = system.maxScaleX;
  101840. outData.minScaleY = system.minScaleY;
  101841. outData.maxScaleY = system.maxScaleY;
  101842. // Life time of each particle (random between...
  101843. outData.minLifeTime = system.minLifeTime;
  101844. outData.maxLifeTime = system.maxLifeTime;
  101845. // Emission rate
  101846. outData.emitRate = system.emitRate;
  101847. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101848. outData.blendMode = system.blendMode;
  101849. // Set the gravity of all particles
  101850. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  101851. // Angular speed, in radians
  101852. outData.minAngularSpeed = system.minAngularSpeed;
  101853. outData.maxAngularSpeed = system.maxAngularSpeed;
  101854. // Speed
  101855. outData.minEmitPower = system.minEmitPower;
  101856. outData.maxEmitPower = system.maxEmitPower;
  101857. outData.updateSpeed = system.updateSpeed;
  101858. switch (system.particleEmitterType.getClassName()) {
  101859. case "BoxEmitter":
  101860. outData.emitterType = "box";
  101861. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  101862. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  101863. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  101864. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  101865. break;
  101866. case "SphereParticleEmitter":
  101867. outData.emitterType = "sphere";
  101868. outData.radius = system.particleEmitterType.radius;
  101869. break;
  101870. case "SphereDirectedParticleEmitter":
  101871. outData.emitterType = "directed_sphere";
  101872. var sphereDirectedParticleEmitter = system.particleEmitterType;
  101873. outData.radius = sphereDirectedParticleEmitter.radius;
  101874. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  101875. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  101876. break;
  101877. case "ConeEmitter":
  101878. outData.emitterType = "cone";
  101879. outData.radius = system.particleEmitterType.radius;
  101880. outData.angle = system.particleEmitterType.angle;
  101881. break;
  101882. default:
  101883. break;
  101884. }
  101885. return outData;
  101886. };
  101887. /**
  101888. * Base Assets URL.
  101889. */
  101890. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  101891. return ParticleHelper;
  101892. }());
  101893. BABYLON.ParticleHelper = ParticleHelper;
  101894. })(BABYLON || (BABYLON = {}));
  101895. //# sourceMappingURL=babylon.particleHelper.js.map
  101896. var BABYLON;
  101897. (function (BABYLON) {
  101898. /**
  101899. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  101900. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  101901. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  101902. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101903. */
  101904. var VideoDome = /** @class */ (function (_super) {
  101905. __extends(VideoDome, _super);
  101906. /**
  101907. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  101908. * @param name Element's name, child elements will append suffixes for their own names.
  101909. * @param urlsOrVideo defines the url(s) or the video element to use
  101910. * @param options An object containing optional or exposed sub element properties
  101911. */
  101912. function VideoDome(name, urlsOrVideo, options, scene) {
  101913. var _this = _super.call(this, name, scene) || this;
  101914. _this._useDirectMapping = false;
  101915. // set defaults and manage values
  101916. name = name || "videoDome";
  101917. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  101918. options.clickToPlay = Boolean(options.clickToPlay);
  101919. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  101920. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  101921. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101922. if (options.useDirectMapping === undefined) {
  101923. _this._useDirectMapping = true;
  101924. }
  101925. else {
  101926. _this._useDirectMapping = options.useDirectMapping;
  101927. }
  101928. // create
  101929. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  101930. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101931. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  101932. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  101933. // configure material
  101934. material.useEquirectangularFOV = true;
  101935. material.fovMultiplier = 1.0;
  101936. material.opacityFresnel = false;
  101937. if (_this._useDirectMapping) {
  101938. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101939. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101940. material.diffuseTexture = texture;
  101941. }
  101942. else {
  101943. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101944. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101945. material.reflectionTexture = texture;
  101946. }
  101947. // configure mesh
  101948. _this._mesh.material = material;
  101949. _this._mesh.parent = _this;
  101950. // optional configuration
  101951. if (options.clickToPlay) {
  101952. scene.onPointerUp = function () {
  101953. _this._videoTexture.video.play();
  101954. };
  101955. }
  101956. return _this;
  101957. }
  101958. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  101959. /**
  101960. * Gets the video texture being displayed on the sphere
  101961. */
  101962. get: function () {
  101963. return this._videoTexture;
  101964. },
  101965. enumerable: true,
  101966. configurable: true
  101967. });
  101968. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  101969. /**
  101970. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101971. * Also see the options.resolution property.
  101972. */
  101973. get: function () {
  101974. return this._material.fovMultiplier;
  101975. },
  101976. set: function (value) {
  101977. this._material.fovMultiplier = value;
  101978. },
  101979. enumerable: true,
  101980. configurable: true
  101981. });
  101982. /**
  101983. * Releases resources associated with this node.
  101984. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101985. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101986. */
  101987. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101988. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101989. this._videoTexture.dispose();
  101990. this._mesh.dispose();
  101991. this._material.dispose();
  101992. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101993. };
  101994. return VideoDome;
  101995. }(BABYLON.Node));
  101996. BABYLON.VideoDome = VideoDome;
  101997. })(BABYLON || (BABYLON = {}));
  101998. //# sourceMappingURL=babylon.videoDome.js.map
  101999. var BABYLON;
  102000. (function (BABYLON) {
  102001. /**
  102002. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  102003. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  102004. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  102005. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102006. */
  102007. var PhotoDome = /** @class */ (function (_super) {
  102008. __extends(PhotoDome, _super);
  102009. /**
  102010. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  102011. * @param name Element's name, child elements will append suffixes for their own names.
  102012. * @param urlsOfPhoto define the url of the photo to display
  102013. * @param options An object containing optional or exposed sub element properties
  102014. */
  102015. function PhotoDome(name, urlOfPhoto, options, scene) {
  102016. var _this = _super.call(this, name, scene) || this;
  102017. _this._useDirectMapping = false;
  102018. // set defaults and manage values
  102019. name = name || "photoDome";
  102020. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102021. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102022. if (options.useDirectMapping === undefined) {
  102023. _this._useDirectMapping = true;
  102024. }
  102025. else {
  102026. _this._useDirectMapping = options.useDirectMapping;
  102027. }
  102028. // create
  102029. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102030. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102031. // configure material
  102032. material.opacityFresnel = false;
  102033. material.useEquirectangularFOV = true;
  102034. material.fovMultiplier = 1.0;
  102035. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  102036. // configure mesh
  102037. _this._mesh.material = material;
  102038. _this._mesh.parent = _this;
  102039. return _this;
  102040. }
  102041. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  102042. /**
  102043. * Gets or sets the texture being displayed on the sphere
  102044. */
  102045. get: function () {
  102046. return this._photoTexture;
  102047. },
  102048. set: function (value) {
  102049. if (this._photoTexture === value) {
  102050. return;
  102051. }
  102052. this._photoTexture = value;
  102053. if (this._useDirectMapping) {
  102054. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102055. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102056. this._material.diffuseTexture = this._photoTexture;
  102057. }
  102058. else {
  102059. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102060. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102061. this._material.reflectionTexture = this._photoTexture;
  102062. }
  102063. },
  102064. enumerable: true,
  102065. configurable: true
  102066. });
  102067. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  102068. /**
  102069. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102070. * Also see the options.resolution property.
  102071. */
  102072. get: function () {
  102073. return this._material.fovMultiplier;
  102074. },
  102075. set: function (value) {
  102076. this._material.fovMultiplier = value;
  102077. },
  102078. enumerable: true,
  102079. configurable: true
  102080. });
  102081. /**
  102082. * Releases resources associated with this node.
  102083. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102084. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102085. */
  102086. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102087. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102088. this._photoTexture.dispose();
  102089. this._mesh.dispose();
  102090. this._material.dispose();
  102091. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102092. };
  102093. return PhotoDome;
  102094. }(BABYLON.Node));
  102095. BABYLON.PhotoDome = PhotoDome;
  102096. })(BABYLON || (BABYLON = {}));
  102097. //# sourceMappingURL=babylon.photoDome.js.map
  102098. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute 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;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n#ifdef BILLBOARD \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.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \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 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;\nvec3 worldPos=position+alignedCorner; \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#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\nvoid main() {\nvUV=uv;\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*size.yz*size.x;\n#ifdef BILLBOARD\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nvec3 yaxis=normalize(initialDirection);\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;\n\nvec4 viewPosition=view*vec4(position+alignedCorner,1.0); \ngl_Position=projection*viewPosition;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform 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 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 CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifdef SIZEGRADIENTS\nout vec3 outInitialSize;\n#endif\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\nin vec3 initialSize;\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() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifdef SIZEGRADIENTS\noutInitialSize=outSize;\n#endif \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*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(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(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(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutInitialSize=initialSize;\noutSize=initialSize*texture(sizeGradientSampler,vec2(age/life,0)).r;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  102099. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=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\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};